Httpclient Post请求

秒速五厘米 2024-04-07 12:28 167阅读 0赞
  1. /*接口调用*/
  2. /**
  3. * post请求以及参数是json
  4. *
  5. * @param url
  6. * @param jsonParams
  7. * @return
  8. */
  9. public static JSONObject doPostForJson(String url, String jsonParams) {
  10. CloseableHttpClient httpClient = HttpClients.createDefault();
  11. JSONObject jsonObject = null;
  12. HttpPost httpPost = new HttpPost(url);
  13. RequestConfig requestConfig = RequestConfig.custom().
  14. setConnectTimeout(180 * 1000).setConnectionRequestTimeout(180 * 1000)
  15. .setSocketTimeout(180 * 1000).setRedirectsEnabled(true).build();
  16. httpPost.setConfig(requestConfig);
  17. httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
  18. try {
  19. httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", "utf-8")));
  20. //System.out.println("request parameters" + EntityUtils.toString(httpPost.getEntity()));
  21. //System.out.println("httpPost:" + httpPost);
  22. HttpResponse response = httpClient.execute(httpPost);
  23. if (response != null && response.getStatusLine().getStatusCode() == 200) {
  24. String result = EntityUtils.toString(response.getEntity());
  25. System.out.println("result:" + result);
  26. jsonObject = JSONObject.fromObject(result);
  27. return jsonObject;
  28. }
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. } finally {
  32. if (null != httpClient) {
  33. try {
  34. httpClient.close();
  35. } catch (IOException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39. return jsonObject;
  40. }
  41. }

发表评论

表情:
评论列表 (有 0 条评论,167人围观)

还没有评论,来说两句吧...

相关阅读