java使用HttpClient传输json格式的参数

感谢博客园的乔叶叶,帮我解决了一个爬虫问题?

原文在此:https://www.cnblogs.com/qiaoyeye/p/4935834.html ,转载请注明出处。


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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值