最近的一个接口项目,传的参数要求是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);
******************************************************************************************************************************************
作者:乔叶叶
博客地址:http://www.cnblogs.com/qiaoyeye/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
******************************************************************************************************************************************