java post httpclient_Java实现HttpClient发送GET、POST请求(https、http)

1 packagecom.sinotn.service;2

3 importcom.alibaba.fastjson.JSONObject;4 importorg.apache.http.HttpEntity;5 importorg.apache.http.NameValuePair;6 importorg.apache.http.client.entity.UrlEncodedFormEntity;7 importorg.apache.http.client.methods.CloseableHttpResponse;8 importorg.apache.http.client.methods.HttpGet;9 importorg.apache.http.client.methods.HttpPost;10 importorg.apache.http.client.utils.URIBuilder;11 importorg.apache.http.entity.StringEntity;12 importorg.apache.http.impl.client.CloseableHttpClient;13 importorg.apache.http.impl.client.HttpClients;14 importorg.apache.http.message.BasicHeader;15 importorg.apache.http.message.BasicNameValuePair;16 importorg.apache.http.util.EntityUtils;17 importorg.slf4j.Logger;18 importorg.slf4j.LoggerFactory;19 importjava.util.ArrayList;20 importjava.util.List;21

22 /**

23 * HttpClient发送GET、POST请求24 * @Author libin25 * @CreateDate 2018.5.28 16:5626 */

27 public classHttpClientService {28

29 private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);30 /**

31 * 返回成功状态码32 */

33 private static final int SUCCESS_CODE = 200;34

35 /**

36 * 发送GET请求37 *@paramurl 请求url38 *@paramnameValuePairList 请求参数39 *@returnJSON或者字符串40 *@throwsException41 */

42 public static Object sendGet(String url, List nameValuePairList) throwsException{43 JSONObject jsonObject = null;44 CloseableHttpClient client = null;45 CloseableHttpResponse response = null;46 try{47 /**

48 * 创建HttpClient对象49 */

50 client =HttpClients.createDefault();51 /**

52 * 创建URIBuilder53 */

54 URIBuilder uriBuilder = newURIBuilder(url);55 /**

56 * 设置参数57 */

58 uriBuilder.addParameters(nameValuePairList);59 /**

60 * 创建HttpGet61 */

62 HttpGet httpGet = newHttpGet(uriBuilder.build());63 /**

64 * 设置请求头部编码65 */

66 httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));67 /**

68 * 设置返回编码69 */

70 httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));71 /**

72 * 请求服务73 */

74 response =client.execute(httpGet);75 /**

76 * 获取响应吗77 */

78 int statusCode =response.getStatusLine().getStatusCode();79

80 if (SUCCESS_CODE ==statusCode){81 /**

82 * 获取返回对象83 */

84 HttpEntity entity =response.getEntity();85 /**

86 * 通过EntityUitls获取返回内容87 */

88 String result = EntityUtils.toString(entity,"UTF-8");89 /**

90 * 转换成json,根据合法性返回json或者字符串91 */

92 try{93 jsonObject =JSONObject.parseObject(result);94 returnjsonObject;95 }catch(Exception e){96 returnresult;97 }98 }else{99 LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败!");100 }101 }catch(Exception e){102 LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);103 } finally{104 response.close();105 client.close();106 }107 return null;108 }109

110 /**

111 * 发送POST请求112 *@paramurl113 *@paramnameValuePairList114 *@returnJSON或者字符串115 *@throwsException116 */

117 public static Object sendPost(String url, List nameValuePairList) throwsException{118 JSONObject jsonObject = null;119 CloseableHttpClient client = null;120 CloseableHttpResponse response = null;121 try{122 /**

123 * 创建一个httpclient对象124 */

125 client =HttpClients.createDefault();126 /**

127 * 创建一个post对象128 */

129 HttpPost post = newHttpPost(url);130 /**

131 * 包装成一个Entity对象132 */

133 StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");134 /**

135 * 设置请求的内容136 */

137 post.setEntity(entity);138 /**

139 * 设置请求的报文头部的编码140 */

141 post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));142 /**

143 * 设置请求的报文头部的编码144 */

145 post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));146 /**

147 * 执行post请求148 */

149 response =client.execute(post);150 /**

151 * 获取响应码152 */

153 int statusCode =response.getStatusLine().getStatusCode();154 if (SUCCESS_CODE ==statusCode){155 /**

156 * 通过EntityUitls获取返回内容157 */

158 String result = EntityUtils.toString(response.getEntity(),"UTF-8");159 /**

160 * 转换成json,根据合法性返回json或者字符串161 */

162 try{163 jsonObject =JSONObject.parseObject(result);164 returnjsonObject;165 }catch(Exception e){166 returnresult;167 }168 }else{169 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");170 }171 }catch(Exception e){172 LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);173 }finally{174 response.close();175 client.close();176 }177 return null;178 }179

180 /**

181 * 组织请求参数{参数名和参数值下标保持一致}182 *@paramparams 参数名数组183 *@paramvalues 参数值数组184 *@return参数对象185 */

186 public static ListgetParams(Object[] params, Object[] values){187 /**

188 * 校验参数合法性189 */

190 boolean flag = params.length>0 && values.length>0 && params.length ==values.length;191 if(flag){192 List nameValuePairList = new ArrayList<>();193 for(int i =0; i

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值