httpClient 请求中加Json


import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpUtils {
   
    private static final String APPLICATION_JSON="application/json";
    private static final String CONTEXT_TYPE_TEXT_JSON="text/json";
    private static HttpClient httpClient;
   
    public static void httpPostWithJson(String url, String json) throws Exception{
        String encoderJson=URLEncoder.encode(json,HTTP.UTF_8);
       
        httpClient=new DefaultHttpClient();
       
        //1、请求头配置
        HttpPost httpPost=new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE,APPLICATION_JSON);
       
        //2、请求体的数据填充
        //StringEntity 是  HttpEntity接口的实现
        StringEntity strEn=new StringEntity(encoderJson);
        strEn.setContentType(CONTEXT_TYPE_TEXT_JSON);
        strEn.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,APPLICATION_JSON));
        httpPost.setEntity(strEn);
       
        //3、执行请求
        HttpResponse response= httpClient.execute(httpPost);
        HttpEntity entity=response.getEntity();
        System.out.println(EntityUtils.getContentCharSet(entity));
    }
   
    public static void main(String[] args){
        String url="http://127.0.0.1:8080/app-pahaoche-rzht/ex/api.do?reqType=effecDateAndEndDate";
        String json="[\"SHZVJ6SMHZ9U5TCLL\",\"SHZVJ6SMHZ9U5TCLL\",\"S0000000000000003\"]";
        try {
            httpPostWithJson(url,json);
            System.out.println("启动请求");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("出现异常");
        }
    }

}

你可能感兴趣的:(httpclient,请求中携带json)