java 客户端发起http请求

  1 package com.mall.core.utils.http;
  2 
  3 import org.apache.commons.lang.StringUtils;
  4 import org.apache.http.HttpResponse;
  5 import org.apache.http.HttpStatus;
  6 import org.apache.http.NameValuePair;
  7 import org.apache.http.client.config.RequestConfig;
  8 import org.apache.http.client.entity.UrlEncodedFormEntity;
  9 import org.apache.http.client.methods.*;
 10 import org.apache.http.entity.StringEntity;
 11 import org.apache.http.impl.client.CloseableHttpClient;
 12 import org.apache.http.impl.client.HttpClients;
 13 import org.apache.http.message.BasicNameValuePair;
 14 import org.apache.http.util.EntityUtils;
 15 import org.apache.logging.log4j.LogManager;
 16 import org.apache.logging.log4j.Logger;
 17 
 18 import javax.servlet.http.HttpServletRequest;
 19 import java.io.IOException;
 20 import java.util.ArrayList;
 21 import java.util.List;
 22 import java.util.Map;
 23 import java.util.Set;
 24 
 25 /**
 26  * Created by admin on 2017/2/22.
    自己写了一个工具类 把常见的几种http请求方法 封装起来
27 */ 28 public class HttpUtils { 29 30 private static final Logger logger = LogManager.getLogger(HttpUtils.class); 31 private static final RequestConfig requestConfig = RequestConfig.custom() 32 .setConnectTimeout(20000).setConnectionRequestTimeout(10000) 33 .setSocketTimeout(20000).build(); 34 35 /** 36 * Http Get 37 * 38 * @param url 请求路径 39 * @param params 参数 40 * @return http响应状态及json结果 41 */ 42 public static HttpResult doGet(String url, Map<String, String> params) { 43 CloseableHttpClient httpClient = HttpClients.createDefault(); 44 url = contactUrl(url, params); 45 HttpGet httpGet = new HttpGet(url.replace(" ", "")); 46 return executeRequest(httpClient, httpGet); 47 } 48 49 /** 50 * Http Post 51 * 52 * @param url 请求路径 53 * @param params 参数 54 * @return http响应状态及json结果 55 */ 56 public static HttpResult doPost(String url, Map<String, String> params) { 57 CloseableHttpClient httpClient = HttpClients.createDefault(); 58 HttpPost httpPost = new HttpPost(url); 59 List<NameValuePair> pairs = new ArrayList<>(); 60 Set<String> keys = params.keySet(); 61 for (String key : keys) { 62 String value = params.get(key); 63 pairs.add(new BasicNameValuePair(key, value)); 64 } 65 return executeRequest(httpClient, httpPost, pairs); 66 } 67 68 /** 69 * Http Put 70 * 71 * @param url 请求路径 72 * @param params 参数 73 * @return http响应状态及json结果 74 */ 75 public static HttpResult doPut(String url, Map<String, String> params) { 76 CloseableHttpClient httpClient = HttpClients.createDefault(); 77 url = contactUrl(url, params); 78 HttpPut httpPut = new HttpPut(url); 79 return executeRequest(httpClient, httpPut); 80 } 81 82 /** 83 * Http Delete 84 * 85 * @param url 请求路径 86 * @param params 参数 87 * @return http响应状态及json结果 88 */ 89 public static HttpResult doDelete(String url, Map<String, String> params) { 90 CloseableHttpClient httpClient = HttpClients.createDefault(); 91 url = contactUrl(url, params); 92 HttpDelete httpDelete = new HttpDelete(url); 93 return executeRequest(httpClient, httpDelete); 94 } 95 96 /** 97 * 拼装url 98 * 99 * @param url url 100 * @param params 参数 101 * @return 102 */ 103 private static String contactUrl(String url, Map<String, String> params) { 104 if (params != null) { 105 String param = ""; 106 Set<String> keys = params.keySet(); 107 for (String key : keys) { 108 String value = params.get(key); 109 if (value == null || value.equals("null")) { 110 continue; 111 } 112 param += key + "=" + value + "&"; 113 } 114 if (!param.equals("")) { 115 url += "?" + param.substring(0, param.length() - 1); 116 } 117 } 118 return url; 119 } 120 private static String contactUrl_(String url, Map<String, Object> params){ 121 if(params != null){ 122 String param = ""; 123 Set<String> keys = params.keySet(); 124 for(String key : keys){ 125 Object value = params.get(key); 126 if(value == null || value.equals("null")){ 127 continue; 128 } 129 param += key + "=" + value + "&"; 130 } 131 if(!param.equals("")){ 132 url += "?" + param.substring(0, param.length() - 1); 133 } 134 } 135 return url; 136 } 137 138 public static String getFullPath(HttpServletRequest request) { 139 String basePath = request.getRequestURL().toString(); 140 String queryString = request.getQueryString(); 141 if (StringUtils.isNotEmpty(queryString)) { 142 queryString = "?" + queryString; 143 } else { 144 queryString = ""; 145 } 146 147 return basePath + queryString; 148 } 149 150 /** 151 * 执行GET/PUT/DELETE请求 152 * 153 * @param httpClient 154 * @param request 155 * @return 156 */ 157 private static HttpResult executeRequest(CloseableHttpClient httpClient, HttpRequestBase request) { 158 HttpResult result = null; 159 request.setConfig(requestConfig); 160 try { 161 HttpResponse response = httpClient.execute(request); 162 int code = response.getStatusLine().getStatusCode(); 163 result = new HttpResult(); 164 result.setStatus(code); 165 if (code == HttpStatus.SC_OK) { 166 result.setResponse(EntityUtils.toString(response.getEntity())); 167 } 168 } catch (Exception e) { 169 logger.error("=========GET/PUT/DELETE请求异常:" + request.getURI(), e); 170 return result; 171 } finally { 172 try { 173 httpClient.close(); 174 } catch (IOException e) { 175 logger.error("=========GET/PUT/DELETE请求连接关闭异常:" + request.getURI(), e); 176 } 177 } 178 logger.debug("========GET/PUT/DELETE请求响应:" + request.getURI() + "\n" + result); 179 return result; 180 } 181 182 /** 183 * 执行POST请求 184 * 185 * @param httpClient 186 * @param request 187 * @param pairs 188 * @return 189 */ 190 private static HttpResult executeRequest(CloseableHttpClient httpClient, HttpEntityEnclosingRequestBase request, List<NameValuePair> pairs) { 191 HttpResult result = null; 192 request.setConfig(requestConfig); 193 try { 194 StringEntity entity; 195 if (pairs.size() == 1 && pairs.get(0).getName().equals("json")) { 196 entity = new StringEntity(pairs.get(0).getValue(), "UTF-8"); 197 entity.setContentType("application/json"); 198 } else { 199 entity = new UrlEncodedFormEntity(pairs, "UTF-8"); 200 } 201 request.setEntity(entity); 202 HttpResponse response = httpClient.execute(request); 203 int code = response.getStatusLine().getStatusCode(); 204 result = new HttpResult(); 205 result.setStatus(code); 206 if (code == HttpStatus.SC_OK) { 207 result.setResponse(EntityUtils.toString(response.getEntity())); 208 } 209 } catch (Exception e) { 210 logger.error("=========POST请求异常:" + request.getURI(), e); 211 return result; 212 } finally { 213 try { 214 httpClient.close(); 215 } catch (IOException e) { 216 logger.error("=========POST请求连接关闭异常:" + request.getURI(), e); 217 } 218 } 219 logger.debug("========POST请求响应:" + request.getURI() + "\n" + result); 220 return result; 221 } 222 }

顺便把 响应的那个HttpResult 类也贴下

public class HttpResult {

    private int status;
    private String response;

    public HttpResult() {
        status = 400;
    }

    public HttpResult(int status, String response) {
        this.status = status;
        this.response = response;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }

    @Override
    public String toString() {
        return "HttpResult{" +
                "status=" + status +
                ", response='" + response + '\'' +
                '}';
    }
}
View Code

 

转载于:https://www.cnblogs.com/dwb91/p/6429434.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值