POST JSON(UTF-8)

某平台对接验证接口,要求POST JSON数据,必须放到body里,记录一下。

 

请求格式如下:

 

POST 请求url HTTP1.1
Content-Type: application/json

{
"aa":"xxx",
"bb":1332406591685,
"cc":{"hh":1,"h2":5,"h3":0},
"dd":{
"mm":"aaaaaaa-bbbb-ccccc"
},
"ss":"1356544548654654654"
}
 

 

代码:

 

public static String doPost(String url, String params) {
         DefaultHttpClient httpclient = new DefaultHttpClient();  
         String body = null;
         
         HttpPost post = postForm(url, params, httpclient);
           
         body = invoke(httpclient, post);  
         
         httpclient.getConnectionManager().shutdown();  
           
         return body;  
     }  
       
     private static String invoke(DefaultHttpClient httpclient,  
             HttpUriRequest httpost) {  
           
         HttpResponse response = sendRequest(httpclient, httpost);  
         String body = paseResponse(response);  
           
         return body;  
     }  
   
     private static String paseResponse(HttpResponse response) {  
         HttpEntity entity = response.getEntity();  
           
         System.out.println("response status: " + response.getStatusLine());
           
         String body = null;  
         try {  
             body = EntityUtils.toString(entity);
         } catch (ParseException e) {  
             e.printStackTrace();  
         } catch (IOException e) {  
             e.printStackTrace();  
         }  
           
         return body;  
     }  
   
     private static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) {  
         HttpResponse response = null;  
         try {  
             response = httpclient.execute(httpost);  
         } catch (ClientProtocolException e) {  
             e.printStackTrace();  
         } catch (IOException e) {  
             e.printStackTrace();  
         }  
         return response;  
     }  
   
     private static HttpPost postForm(String url, String body, HttpClient httpclient){  
         HttpPost httpost = null;
         try {
			HttpParams params = httpclient.getParams();
			HttpConnectionParams.setConnectionTimeout(params, 20000);
			HttpConnectionParams.setSoTimeout(params, 20000);
			httpost = new HttpPost(url);
			httpost.setHeader("Content-Type", "application/x-www-form-urlencoded");
			httpost.setEntity(new ByteArrayEntity(body.getBytes("UTF-8")));
         } catch (UnsupportedEncodingException e) {
             e.printStackTrace();  
         }  
         return httpost;  
     }

 

所需jar包:

1.commons-logging-1.1.1.jar

2.commons-codec-1.6.jar

3.httpclient-4.2.jar

4.httpcore-4.2.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值