| | |
| | | return httpClient; |
| | | } |
| | | |
| | | /** |
| | | * json的post请求(只关心是否成功,非200直接抛异常) |
| | | * |
| | | * @param url 请求url |
| | | * @param request 请求报文 |
| | | * @return 固定返回true(http状态非200会抛HttpRequestException) |
| | | */ |
| | | public static Boolean postJsonRequest(String url, String request) throws HttpRequestException { |
| | | postJsonRequestForString(url, request); |
| | | return true; |
| | | } |
| | | |
| | | /** |
| | | * json的post请求,返回响应报文内容(用于需要解析返回码的场景,如云MAS短信) |
| | | * |
| | | * @param url 请求url |
| | | * @param request 请求报文 |
| | | * @return 响应报文内容 |
| | | */ |
| | | public static String postJsonRequestForString(String url, String request) throws HttpRequestException { |
| | | Assert.hasLength(url, "请求url不能为空字符串。"); |
| | | EntityEnclosingMethod httpMethod = new PostMethod(url); |
| | | |
| | |
| | | String respJson = stringBuffer.toString(); |
| | | // String respJson = httpMethod.getResponseBodyAsString(); |
| | | if (resultCode == OK) { |
| | | return true; |
| | | return respJson; |
| | | } else { |
| | | log.warn("【postJsonRequestForString】请求失败,url:{},状态码:{},响应:{}", url, resultCode, respJson); |
| | | throw new HttpRequestException(resultCode, respJson); |
| | | } |
| | | } catch (UnsupportedEncodingException e) { |
| | |
| | | |
| | | // 获取响应码 |
| | | int responseCode = connection.getResponseCode(); |
| | | log.info("postFormRequest 响应码:{},url:{}", responseCode, fullUrl); |
| | | |
| | | // 读取响应 |
| | | // 读取响应(非200时errorStream可能为null,避免NPE) |
| | | StringBuilder response = new StringBuilder(); |
| | | if (responseCode == HttpURLConnection.HTTP_OK) { |
| | | reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); |
| | | } else { |
| | | reader = new BufferedReader(new InputStreamReader(connection.getErrorStream())); |
| | | InputStream respStream = responseCode == HttpURLConnection.HTTP_OK |
| | | ? connection.getInputStream() |
| | | : connection.getErrorStream(); |
| | | if (respStream == null) { |
| | | log.warn("postFormRequest 响应体为空,响应码:{},url:{}", responseCode, fullUrl); |
| | | return ""; |
| | | } |
| | | reader = new BufferedReader(new InputStreamReader(respStream)); |
| | | |
| | | String line; |
| | | while ((line = reader.readLine()) != null) { |