HttpClient的get+post请求使用
啥都不说,先上代码
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.util.ArrayList; 5 import java.util.List; 6 import java.util.Map; 7 8 import org.apache.http.HttpEntity; 9 import org.apache.http.HttpStatus; 10 import org.apache.http.NameValuePair; 11 import org.apache.http.client.ClientProtocolException; 12 import org.apache.http.client.entity.UrlEncodedFormEntity; 13 import org.apache.http.client.methods.CloseableHttpResponse; 14 import org.apache.http.client.methods.HttpGet; 15 import org.apache.http.client.methods.HttpPost; 16 import org.apache.http.client.methods.HttpRequestBase; 17 import org.apache.http.config.Registry; 18 import org.apache.http.config.RegistryBuilder; 19 import org.apache.http.conn.socket.ConnectionSocketFactory; 20 import org.apache.http.conn.socket.PlainConnectionSocketFactory; 21 import org.apache.http.entity.StringEntity; 22 import org.apache.http.impl.client.CloseableHttpClient; 23 import org.apache.http.impl.client.HttpClientBuilder; 24 import org.apache.http.impl.client.HttpClients; 25 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 26 import org.apache.http.message.BasicNameValuePair; 27 import org.apache.http.util.EntityUtils; 28 import org.apache.log4j.Logger; 29 30 import com.alibaba.fastjson.JSONObject; 31 32 /** 33 * http请求工具类 34 * Created by swordxu on 15/8/5. 35 */ 36 public class HttpClientUtils { 37 private static Logger logger = Logger.getLogger(HttpClientUtils.class); 38 39 //设置连接池线程最大数量 40 private static final int MAX_TOTAL = 500; 41 //设置单个路由最大的连接线程数量 42 private static final int MAX_ROUTE_TOTAL = 500; 43 44 private static final int REQUEST_TIMEOUT = 25000; 45 46 private static final int REQUEST_SOCKET_TIME = 25000; 47 48 private static final String ENCODING_UTF_8 = "UTF-8"; 49 50 private static HttpClientBuilder httpBulder = null; 51 private static CloseableHttpClient httpClient = null; 52 53 static{ 54 55 if (httpClient == null) { 56 ConnectionSocketFactory httpFactory = PlainConnectionSocketFactory.getSocketFactory(); 57 58 Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", httpFactory).build(); 59 PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); 60 cm.setMaxTotal(MAX_TOTAL); 61 62 cm.setDefaultMaxPerRoute(MAX_ROUTE_TOTAL); 63 64 httpClient = HttpClients.custom().setConnectionManager(cm) 65 .disableAutomaticRetries().build(); 66 } 67 68 } 69 70 /** 71 * get请求方式 72 * @param uri 请求url 73 * @return 74 */ 75 public String doGet(String uri) throws Exception{ 76 long b = System.currentTimeMillis(); 77 //CloseableHttpClient httpClient = null; 78 CloseableHttpResponse response = null; 79 HttpGet httpget = null; 80 try { 81 logger.debug("executing get request uri :" + uri); 82 83 httpget = new HttpGet(uri); 84 //httpClient = HttpClients.createDefault(); 85 response = httpClient.execute(httpget); 86 87 if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 88 HttpEntity entity = response.getEntity(); 89 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING_UTF_8)); 90 String line = null; 91 StringBuilder sb = new StringBuilder(); 92 while ((line = reader.readLine()) != null) { 93 sb.append(line); 94 } 95 logger.debug("response body :" + sb); 96 long e = System.currentTimeMillis(); 97 logger.debug("executing post request time:" + (e -b)); 98 99 EntityUtils.consume(entity);//关闭httpEntity流 100 101 return sb.toString(); 102 }else{ 103 throw new Exception(response.getStatusLine().getStatusCode()+""); 104 } 105 } catch (ClientProtocolException e) { 106 logger.error("Failed to get request uri: "+uri,e); 107 throw new RuntimeException("Failed to post request uri: "+uri,e); 108 } catch (IOException e) { 109 logger.error("Failed to get request uri: "+uri,e); 110 throw new RuntimeException("Failed to post request uri: "+uri,e); 111 }finally { 112 close(httpget,response); 113 } 114 } 115 /** 116 * post 请求并返回实体对象 117 * @param url 请求url 118 * @param paramaters 请求参数 119 * @param clazz 返回Class 120 * @return 121 * @throws Exception 122 */ 123 public static <T> T doPost(String url, Map<String, String> paramaters,Class<T> clazz) throws Exception{ 124 String ret = post(url, paramaters, null); 125 return null != ret ? JSONObject.parseObject(ret, clazz) : null; 126 } 127 128 /** 129 * 发送POST请求 130 * @param uri 131 * @return 132 */ 133 public static String post(String uri) throws Exception{ 134 return post(uri, null); 135 } 136 137 /** 138 * 发送POST请求 139 * @param uri 140 * @param paramMap 请求参数 141 * @return 142 */ 143 public static String post(String uri, Map<String, String> paramMap) throws Exception{ 144 return post(uri, paramMap, null); 145 } 146 147 /** 148 * post 请求 149 * @param uri 请求url 150 * @param paramMap 请求参数 151 * @param charset 请求编码 152 * @return 153 * @throws Exception 154 */ 155 public static String post(String uri, Map<String, String> paramMap,String charset) throws Exception{ 156 long b = System.currentTimeMillis(); 157 CloseableHttpResponse response = null; 158 //CloseableHttpClient httpClient = null; 159 HttpPost httpPost = null; 160 try { 161 logger.debug("executing post request url:"+uri); 162 163 httpPost = new HttpPost(uri); 164 httpPost.setEntity(new UrlEncodedFormEntity(handleData(paramMap),null == charset ? ENCODING_UTF_8 : charset)); 165 166 //httpClient = HttpClients.createDefault(); 167 response = httpClient.execute(httpPost); 168 if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 169 HttpEntity entity = response.getEntity(); 170 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING_UTF_8)); 171 String line = null; 172 StringBuilder sb = new StringBuilder(); 173 while ((line = reader.readLine()) != null) { 174 sb.append(line); 175 } 176 logger.debug("response body :" + sb); 177 long e = System.currentTimeMillis(); 178 logger.debug("executing post request time:" + (e -b)); 179 180 EntityUtils.consume(entity);//关闭流 181 182 return sb.toString(); 183 }else{ 184 throw new Exception(response.getStatusLine().getStatusCode()+""); 185 } 186 } catch (Exception e) { 187 throw e; 188 }finally{ 189 close(httpPost,response); 190 } 191 } 192 193 /** 194 * post 请求 195 * @param url 196 * @param params 197 * @return 198 */ 199 public static String doPost(String url, Map<String, String> params) throws Exception{ 200 return post(url, params, null); 201 } 202 203 /** 204 * post 请求 205 * @param url 206 * @param json 207 * @return 208 */ 209 public static <T> T doPost(String url, String json, Class<T> clazz) throws Exception{ 210 String ret = doPost(url, json); 211 return null != ret ? JSONObject.parseObject(ret, clazz) : null; 212 } 213 214 /** 215 * post 请求 216 * @param url 217 * @param json 218 * @return 219 */ 220 public static String doPost(String url, String json) throws Exception{ 221 CloseableHttpResponse response = null; 222 HttpPost httpPost = null; 223 long b = System.currentTimeMillis(); 224 try { 225 logger.debug("executing post request url:" + url); 226 227 StringEntity s = new StringEntity(json,"UTF-8"); 228 s.setContentType("application/json"); 229 230 httpPost = new HttpPost(url); 231 httpPost.setEntity(s); 232 233 //httpClient = HttpClients.createDefault(); 234 response = httpClient.execute(httpPost); 235 236 if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 237 HttpEntity entity = response.getEntity(); 238 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING_UTF_8)); 239 String line = null; 240 StringBuilder sb = new StringBuilder(); 241 while ((line = reader.readLine()) != null) { 242 sb.append(line); 243 } 244 logger.debug("response body :" + sb); 245 long e = System.currentTimeMillis(); 246 logger.debug("executing post request time:" + (e -b)); 247 248 EntityUtils.consume(entity);//关闭流 249 250 return sb.toString(); 251 }else{ 252 throw new Exception(response.getStatusLine().getStatusCode()+""); 253 } 254 }finally{ 255 close(httpPost,response); 256 } 257 } 258 259 /** 260 * 处理map数据 261 * @param postData 请求数据 262 * @return 263 */ 264 private static List<NameValuePair> handleData(Map<String, String> postData) { 265 List<NameValuePair> datas = new ArrayList<NameValuePair>(); 266 for (Map.Entry<String,String> entry : postData.entrySet()) { 267 datas.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 268 } 269 return datas; 270 } 271 /** 272 * 关闭链接 273 * @param request 274 * @param response 275 */ 276 private static void close(HttpRequestBase request,CloseableHttpResponse response){ 277 if(null != response){ 278 try { 279 response.close(); 280 } catch (IOException e) { 281 e.printStackTrace(); 282 } 283 } 284 if(null != request){ 285 request.releaseConnection(); 286 } 287 }
1、http的静态变量的相关设置
static{ if (httpClient == null) { ConnectionSocketFactory httpFactory = PlainConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", httpFactory).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); cm.setMaxTotal(MAX_TOTAL); cm.setDefaultMaxPerRoute(MAX_ROUTE_TOTAL); httpClient = HttpClients.custom().setConnectionManager(cm) .disableAutomaticRetries().build(); } }
2.httpCliet的调用
String strResult = ""; JSONObject jobj = new JSONObject(); jobj.put("wxacc", wxacc); jobj.put("password", password); jobj.put("smallClassId", smallClassId); jobj.put("reportName", reportName); jobj.put("mobile", mobile); jobj.put("address", address); jobj.put("description", description); jobj.put("position", position); jobj.put("files", files); jobj.put("wxEvtFileList", wxEvtFileList); jobj.put("isreceipt", "true"); String conResult; try { conResult = HttpClientUtils.doPost(saveEvtPreUrl, jobj.toJSONString()); Head head = JSON.parseObject(conResult, Head.class); logger.debug(head.toString()); } catch (Exception e) { e.printStackTrace(); } return strResult;
完~