如何使用HttpClient包实现JAVA发起HTTP请求?

java

今天在搭建公司项目框架的时候,发现缺少了一个Java发送HTTP请求的工具类,在网上找了一通,经过自己的改造,已经能实现get请求和post请求的了,现在将代码贴在这里。给大家参考。

  1 package com.sunyard.util;

2

3 import com.sunyard.constans.Constants;

4

5 import org.apache.commons.httpclient.*;

6 import org.apache.commons.httpclient.methods.GetMethod;

7 import org.apache.commons.httpclient.methods.PostMethod;

8 import org.apache.commons.httpclient.methods.RequestEntity;

9 import org.apache.commons.httpclient.methods.StringRequestEntity;

10 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

11 import org.apache.commons.lang.StringUtils;

12 import org.apache.logging.log4j.LogManager;

13 import org.apache.logging.log4j.Logger;

14

15 import java.io.IOException;

16 import java.net.URL;

17

18 public class HTTPUtils {

19

20 private final static Logger logger = LogManager.getLogger(Constants.LOGNAME);

21

22 private final static String OPERATER_NAME = "【HTTP操作】";

23

24 private final static int SUCCESS = 200;

25

26 private final static String UTF8 = "UTF-8";

27

28 private HttpClient client;

29

30 private static HTTPUtils instance = new HTTPUtils();

31

32 /**

33 * 私有化构造器

34 */

35 private HTTPUtils() {

36

37 HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();

38 HttpConnectionManagerParams params = httpConnectionManager.getParams();

39 params.setConnectionTimeout(5000);

40 params.setSoTimeout(20000);

41 params.setDefaultMaxConnectionsPerHost(1000);

42 params.setMaxTotalConnections(1000);

43 client = new HttpClient(httpConnectionManager);

44 client.getParams().setContentCharset(UTF8);

45 client.getParams().setHttpElementCharset(UTF8);

46 }

47

48 /**

49 * get请求

50 */

51 public static String get(URL url) {

52 return instance.doGet(url);

53 }

54

55 private String doGet(URL url) {

56 long beginTime = System.currentTimeMillis();

57 String respStr = StringUtils.EMPTY;

58 try {

59 logger.info(OPERATER_NAME + "开始get通信,目标host:" + url);

60 HttpMethod method = new GetMethod(url.toString());

61 // 中文转码

62 method.getParams().setContentCharset(UTF8);

63 try {

64 client.executeMethod(method);

65 } catch (HttpException e) {

66

67 logger.error(new StringBuffer("发送HTTP GET给\r\n").append(url)

68 .append("\r\nHTTP异常\r\n"), e);

69 } catch (IOException e) {

70

71 logger.error(new StringBuffer("发送HTTP GET给\r\n").append(url)

72 .append("\r\nIO异常\r\n"), e);

73 }

74 if (method.getStatusCode() == SUCCESS) {

75 respStr = method.getResponseBodyAsString();

76 }

77 // 释放连接

78 method.releaseConnection();

79

80 logger.info(OPERATER_NAME + "通讯完成,返回码:" + method.getStatusCode());

81 logger.info(OPERATER_NAME + "返回内容:" + method.getResponseBodyAsString());

82 logger.info(OPERATER_NAME + "结束..返回结果:" + respStr);

83 } catch (Exception e) {

84 logger.info(OPERATER_NAME, e);

85 }

86 long endTime = System.currentTimeMillis();

87 logger.info(OPERATER_NAME + "共计耗时:" + (endTime - beginTime) + "ms");

88

89 return respStr;

90 }

91

92

93 /**

94 * POST请求

95 */

96 public static String post(URL url, String content) {

97 return instance.doPost(url, content);

98 }

99

100 private String doPost(URL url, String content) {

101 long beginTime = System.currentTimeMillis();

102 String respStr = StringUtils.EMPTY;

103 try {

104 logger.info(OPERATER_NAME + "开始post通信,目标host:" + url.toString());

105 logger.info("通信内容:" + content);

106 PostMethod post = new PostMethod(url.toString());

107 RequestEntity requestEntity = new StringRequestEntity(content, "application/json;charse=UTF-8", UTF8);

108 post.setRequestEntity(requestEntity);

109 // 设置格式

110 post.getParams().setContentCharset(UTF8);

111

112 client.executeMethod(post);

113 if (post.getStatusCode() == SUCCESS) {

114 respStr = post.getResponseBodyAsString();

115 }

116

117 logger.info(OPERATER_NAME + "通讯完成,返回码:" + post.getStatusCode());

118 logger.info(OPERATER_NAME + "返回内容:" + post.getResponseBodyAsString());

119 logger.info(OPERATER_NAME + "结束..返回结果:" + respStr);

120 post.releaseConnection();

121

122 } catch (Exception e) {

123 logger.error(OPERATER_NAME, e);

124 }

125 long endTime = System.currentTimeMillis();

126 logger.info(OPERATER_NAME + "共计耗时:" + (endTime - beginTime) + "ms");

127 return respStr;

128 }

129

130 }

 jar依赖如图

编写测试类测试:

1  public static void main(String[] args) throws Exception {

2 JSONObject json = new JSONObject();

3 json.put("action", "test");

4 URL url = new URL("http://localhost:8080/TPSServer/door.do");

5 String resp = post(url, json.toString());

6 System.out.println(resp);

7 }

控制台输出结果:

1 2017-07-26 11:17:09 GMT+08:00 INFO  com.sunyard.util.HTTPUtils 106 doPost - 【HTTP操作】开始post通信,目标host:http://localhost:8080/TPSServer/door.do

2 2017-07-26 11:17:09 GMT+08:00 INFO com.sunyard.util.HTTPUtils 107 doPost - 通信内容:{"action":"test"}

3 2017-07-26 11:17:10 GMT+08:00 INFO com.sunyard.util.HTTPUtils 119 doPost - 【HTTP操作】通讯完成,返回码:200

4 2017-07-26 11:17:10 GMT+08:00 INFO com.sunyard.util.HTTPUtils 120 doPost - 【HTTP操作】返回内容:{"errorcode":"0","errormsg":"success"}

5 2017-07-26 11:17:10 GMT+08:00 INFO com.sunyard.util.HTTPUtils 121 doPost - 【HTTP操作】结束..返回结果:{"errorcode":"0","errormsg":"success"}

6 2017-07-26 11:17:10 GMT+08:00 INFO com.sunyard.util.HTTPUtils 128 doPost - 【HTTP操作】共计耗时:579ms

7 {"errorcode":"0","errormsg":"success"}

HttpClient工具包的使用,请大家参考。

from: https://www.cnblogs.com/yujiwei/p/7238613.html

以上是 如何使用HttpClient包实现JAVA发起HTTP请求? 的全部内容, 来源链接: utcz.com/z/390118.html

回到顶部