最近的一個介面專案,傳的引數要求是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);
} }