java使用HttpClient傳輸json格式的參數


最近的一個接口項目,傳的參數要求是json,需要特殊處理一下。

重點是這兩句話:

httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
se.setContentType(CONTENT_TYPE_TEXT_JSON);這兩句話的作用與jmeter的設置header信息類似
package com.base;

import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;

/** 
 * @author QiaoJiafei 
 * @version 創建時間:2015年11月4日 下午1:55:45 
 * 類說明 
 */
public class HttpGetByJson {
      public static void main(String args[]) throws Exception{
          final String CONTENT_TYPE_TEXT_JSON = "text/json";
          DefaultHttpClient client = new DefaultHttpClient(
                  new PoolingClientConnectionManager());
          
          String url = "http://172.16.30.226:8091/svc/authentication/register";
        String js = "{\"userName\":\"18600363833\",\"validateChar\":\"706923\",\"randomChar\":\"706923\",\"password\":\"123456\",\"confirmPwd\":\"123456\",\"recommendMobile\":\"\",\"idCard\":\"320601197608285792\",\"realName\":\"闕岩\",\"verifyCode\"}";
          
        HttpPost httpPost = new HttpPost(url);       
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
               
        StringEntity se = new StringEntity(js);
        se.setContentType(CONTENT_TYPE_TEXT_JSON);

        httpPost.setEntity(se);
        
        CloseableHttpResponse response2 = null;
        
        response2 = client.execute(httpPost);
        HttpEntity entity2 = null;
        entity2 = response2.getEntity();
        String s2 = EntityUtils.toString(entity2, "UTF-8");
        System.out.println(s2);
      }
      

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM