某平台对接验证接口,要求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