最近的一个接口项目,传的参数要求是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); } }
时间: 2024-11-09 22:10:36