httpclient案例二(调用百度地图的接口)
2017-11-23 15:38
495 查看
一,class T
1 package com.http.test; 2 3 import org.junit.Test; 4 5 import com.http.BaiduMapProxyService; 6 import com.http.BaiduMapService; 7 8 public class T { 9 10 /** 11 * 测试插入数据 12 */ 13 @Test 14 public void testInsert(){ 15 BaiduMapService baiduMapService= new BaiduMapService(); 16 //随便写的经纬度 17 baiduMapService.insertLocation("武汉纺织大学5号宿舍楼", "116.428415", "39.927109", "北京"); 18 } 19 20 /** 21 * 测试获得数据 22 */ 23 @Test 24 public void testGet(){ 25 BaiduMapService baiduMapService= new BaiduMapService(); 26 baiduMapService.findNearBySchool("116.428415", "39.927109"); 27 } 28 29 /** 30 * 代理测试插入数据 31 */ 32 @Test 33 public void testProxyInsert(){ 34 BaiduMapProxyService baiduMapService= new BaiduMapProxyService(); 35 36 //随便写的经纬度 37 baiduMapService.insertLocation("武汉纺织大学5号宿舍楼", "116.428415", "39.927109", "北京"); 38 } 39 40 /** 41 * 测试获得数据 42 */ 43 @Test 44 public void testProxyGet(){ 45 BaiduMapProxyService baiduMapService= new BaiduMapProxyService(); 46 baiduMapService.findNearBySchool("116.428415", "39.927109"); 47 } 48 }
二,request
1 package com.http; 2 3 import java.util.Arrays; 4 import java.util.LinkedHashMap; 5 import java.util.Map; 6 7 /** 8 * Requst分装类,封装一些信息 9 * 作者:Administrator<br> 10 * 版本:1.0<br> 11 * 创建日期:下午9:24:43<br> 12 */ 13 public class Request { 14 15 16 /**请求属性*/ 17 private Map<String, String> properties; 18 19 /**请求参数*/ 20 private Map<String, String> params ; 21 22 /**请求头部*/ 23 private Map<String, String> headers; 24 25 private byte[] postData; 26 27 /**是否同步*/ 28 private boolean sync=false; 29 30 31 /** 32 * 获得设置的属性 33 * @param property 34 * @return 35 */ 36 public String getProperty(String property) { 37 if(properties ==null){ 38 return null; 39 } 40 return properties.get(property); 41 } 42 43 /** 44 * 设置属性 45 * @param propery 46 * @param value 47 */ 48 public void setProperty(String propery,String value) { 49 if(properties==null){ 50 properties = new LinkedHashMap<String, String>(); 51 } 52 properties.put(propery, value); 53 } 54 55 56 /** 57 * 设置参数 58 * @param params 59 */ 60 public void setParam(String param,String value) { 61 if(params==null){ 62 params = new LinkedHashMap<String, String>(); 63 } 64 params.put(param, value); 65 } 66 67 public Map<String, String> getHeaders() { 68 return headers; 69 } 70 71 /** 72 * 设置头部信息 73 * @param header 74 * @param value 75 */ 76 public void setHeader(String header, String value) { 77 if (headers == null) { 78 headers = new LinkedHashMap<String, String>(); 79 } 80 headers.put(header, value); 81 } 82 83 public Map<String, String> getParams() { 84 return params; 85 } 86 87 public String getHeader(String header) { 88 if (headers == null) { 89 return null; 90 } 91 return headers.get(header); 92 } 93 public Map<String, String> getProperties() { 94 return properties; 95 } 96 97 public void setProperties(Map<String, String> properties) { 98 this.properties = properties; 99 } 100 101 public void setParams(Map<String, String> params) { 102 this.params = params; 103 } 104 105 public void setHeaders(Map<String, String> headers) { 106 this.headers = headers; 107 } 108 109 110 111 public byte[] getPostData() { 112 return postData; 113 } 114 115 public void setPostData(byte[] postData) { 116 this.postData = postData; 117 } 118 119 public boolean isSync() { 120 return sync; 121 } 122 123 public void setSync(boolean sync) { 124 this.sync = sync; 125 } 126 127 128 129 130 131 }
三,response
1 package com.http; 2 3 import java.util.LinkedHashMap; 4 import java.util.Map; 5 6 /** 7 * 响应类 8 * 作者:Administrator<br> 9 * 版本:1.0<br> 10 * 创建日期:下午9:36:03<br> 11 */ 12 public class Response { 13 14 /**响应码*/ 15 private int statusCode ; 16 17 /**响应内容*/ 18 private byte[] content ; 19 20 /**响应头部*/ 21 private Map<String, String> headers; 22 23 /** 24 * 设置响应头 25 * 26 * @param name 27 * @param value 28 */ 29 public void setHeader(String name, String value) { 30 if (headers == null) { 31 headers = new LinkedHashMap<String, String>(); 32 } 33 headers.put(name, value); 34 } 35 36 /** 37 * 按指定编码获得响应内容,有些响应乱码了 需要解决乱码问题 38 * @param encoding 39 * @return 40 */ 41 public String getContentString(String encoding) { 42 try { 43 String contentString = new String(getContent(), encoding); 44 return contentString; 45 } catch (Exception e) { 46 System.out.println("不支持编码"); 47 } 48 return null; 49 } 50 51 public int getStatusCode() { 52 return statusCode; 53 } 54 55 public void setStatusCode(int statusCode) { 56 this.statusCode = statusCode; 57 } 58 59 public byte[] getContent() { 60 return content; 61 } 62 63 public void setContent(byte[] content) { 64 this.content = content; 65 } 66 67 public Map<String, String> getHeaders() { 68 return headers; 69 } 70 71 public void setHeaders(Map<String, String> headers) { 72 this.headers = headers; 73 } 74 75 76 }
四,BaiduMapService
1 package com.http; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import org.apache.http.NameValuePair; 7 import org.apache.http.message.BasicNameValuePair; 8 9 10 /** 11 * 12 * title:百度地图服务类 <br> 13 * 版权: Copyright (c) 2011-2016<br> 14 * 15 * @author:Administrator<br> 16 * @date:Apr 7, 2016<br> 17 */ 18 public class BaiduMapService { 19 20 /** 21 * 请求发送类 22 */ 23 private HttpClientUtil httpClientUtil=new HttpClientUtil(); 24 25 public String insertLocation(String title, String longitude, 26 String latitude, String address) { 27 //插入数据接口 28 String url = "http://api.map.baidu.com/geodata/v3/poi/create"; 29 Request request=new Request(); 30 //数据 31 request.setProperty("url", url); 32 request.setProperty("method", "post"); 33 //我自己的百度云数据库名称 34 request.setParam("geotable_id", "137287"); 35 request.setParam("ak", "GShGXR4uNroTq4mzqsf1v7h3VgsC3aIk"); 36 request.setParam("latitude", latitude); 37 request.setParam("longitude", longitude); 38 request.setParam("address", address); 39 request.setParam("coord_type", "3"); 40 request.setParam("title", title); 41 42 Response response; 43 try { 44 response = httpClientUtil.sendRequest(request); 45 if(response==null||response.getStatusCode()!=200){ 46 return null; 47 } 48 String content =response.getContentString("utf-8"); 49 System.out.println("返回的数据是:"+StringUtils.decodeUnicode(content)); 50 return content; 51 } catch (Exception e) { 52 // TODO Auto-generated catch block 53 e.printStackTrace(); 54 } 55 56 return null; 57 58 } 59 60 /** 61 * 根据经纬度查周边学校半径500米 62 * 63 * @return 64 */ 65 public String findNearBySchool(String longitude, String latitude) { 66 String url = "http://api.map.baidu.com/geosearch/v3/nearby?geotable_id=137287&ak=GShGXR4uNroTq4mzqsf1v7h3VgsC3aIk&radius=500&location=" 67 + longitude + "," + latitude; 68 69 70 71 Request request=new Request(); 72 request.setProperty("url", url); 73 request.setProperty("method", "get"); 74 75 Response response=new Response(); 76 77 try { 78 response = httpClientUtil.sendRequest(request); 79 if(response==null||response.getStatusCode()!=200){ 80 return null; 81 } 82 83 String content =response.getContentString("utf-8"); 84 System.out.println("返回的数据是:"+StringUtils.decodeUnicode(content)); 85 return content; 86 } catch (Exception e) { 87 // TODO Auto-generated catch block 88 e.printStackTrace(); 89 } 90 return null; 91 92 } 93 }
五,HttpClientUtil
1 package com.http; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.EOFException; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.InterruptedIOException; 8 import java.io.UnsupportedEncodingException; 9 import java.net.SocketException; 10 import java.net.URI; 11 import java.net.URISyntaxException; 12 import java.net.UnknownHostException; 13 import java.security.KeyManagementException; 14 import java.security.NoSuchAlgorithmException; 15 import java.security.cert.X509Certificate; 16 import java.util.ArrayList; 17 import java.util.List; 18 import java.util.Map; 19 import java.util.Map.Entry; 20 import java.util.regex.Matcher; 21 import java.util.regex.Pattern; 22 import java.util.zip.GZIPInputStream; 23 24 import javax.net.ssl.SSLContext; 25 import javax.net.ssl.SSLException; 26 import javax.net.ssl.SSLHandshakeException; 27 import javax.net.ssl.TrustManager; 28 import javax.net.ssl.X509TrustManager; 29 30 import org.apache.commons.io.IOUtils; 31 import org.apache.commons.lang.StringUtils; 32 import org.apache.http.Header; 33 import org.apache.http.HttpEntity; 34 import org.apache.http.HttpEntityEnclosingRequest; 35 import org.apache.http.HttpHost; 36 import org.apache.http.HttpRequest; 37 import org.apache.http.HttpResponse; 38 import org.apache.http.NameValuePair; 39 import org.apache.http.NoHttpResponseException; 40 import org.apache.http.ParseException; 41 import org.apache.http.ProtocolException; 42 import org.apache.http.client.ClientProtocolException; 43 import org.apache.http.client.CookieStore; 44 import org.apache.http.client.HttpRequestRetryHandler; 45 import org.apache.http.client.config.CookieSpecs; 46 import org.apache.http.client.config.RequestConfig; 47 import org.apache.http.client.config.RequestConfig.Builder; 48 import org.apache.http.client.entity.UrlEncodedFormEntity; 49 import org.apache.http.client.methods.CloseableHttpResponse; 50 import org.apache.http.client.methods.HttpGet; 51 import org.apache.http.client.methods.HttpPost; 52 import org.apache.http.client.protocol.HttpClientContext; 53 import org.apache.http.conn.ConnectTimeoutException; 54 import org.apache.http.conn.HttpHostConnectException; 55 import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 56 import org.apache.http.cookie.Cookie; 57 import org.apache.http.entity.ByteArrayEntity; 58 import org.apache.http.impl.client.BasicCookieStore; 59 import org.apache.http.impl.client.CloseableHttpClient; 60 import org.apache.http.impl.client.DefaultRedirectStrategy; 61 import org.apache.http.impl.client.HttpClientBuilder; 62 import org.apache.http.impl.client.HttpClients; 63 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 64 import org.apache.http.message.BasicNameValuePair; 65 import org.apache.http.protocol.HttpContext; 66 import org.apache.http.util.ByteArrayBuffer; 67 import org.apache.http.util.EntityUtils; 68 69 /** 70 * HttpClient工具封装类,Post,Get请求,代理请求 71 * 作者:<br> 72 * 版本:1.0<br> 73 * 创建日期:下午9:21:00<br> 74 */ 75 public class HttpClientUtil { 76 77 /***连接超时时间*/ 78 private Integer connectTimeout =60*1000; 79 80 private Integer socketTimeout =180*1000; 81 private CloseableHttpClient httpClient = null; 82 83 private CookieStore cookieStore = new BasicCookieStore(); 84 85 86 /** 代理请求 */ 87 public HttpClientUtil(String proxyHost, int proxyPort) { 88 this(proxyHost, proxyPort, -1, -1, 0, 0, true); 89 } 90 91 /** 默认*/ 92 public HttpClientUtil() { 93 this(null, 0, -1, -1, 0, 0, true); 94 } 95 96 /** 进行请求无代理设置连接时间 */ 97 public HttpClientUtil(int socketTimeout, int connectTimeout) { 98 this(null, 0, socketTimeout, connectTimeout, 0, 0, true); 99 } 100 101 102 /** 103 * 104 * @param proxyHost 代理主机地址 105 * @param proxyPort 代理端口 106 * @param socketTimeout 107 * @param connectTimeout 108 * @param route 109 * @param maxTotal 110 * @param followRedirect 111 */ 112 public HttpClientUtil(String proxyHost, int proxyPort, int socketTimeout, int connectTimeout, int route, int maxTotal, boolean followRedirect){ 113 Builder builder = RequestConfig.custom(); 114 builder.setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY); 115 if (followRedirect) { 116 builder.setCircularRedirectsAllowed(true); 117 builder.setMaxRedirects(100); 118 } 119 if (StringUtils.isNotBlank(proxyHost) && proxyPort > 0) { 120 builder.setProxy(new HttpHost(proxyHost, proxyPort)); 121 } 122 123 //设置连接时间 124 if (socketTimeout != -1) { 125 this.socketTimeout = socketTimeout; 126 } 127 builder.setSocketTimeout(this.socketTimeout); 128 129 if (connectTimeout != -1) { 130 this.connectTimeout = connectTimeout; 131 } 132 builder.setConnectTimeout(this.connectTimeout); 133 builder.setConnectionRequestTimeout(this.connectTimeout); 134 135 RequestConfig requestConfig = builder.build(); 136 init(requestConfig, route, maxTotal); 137 } 138 139 private void init(RequestConfig requestConfig, int route, int maxTotal) { 140 X509TrustManager x509mgr = new X509TrustManager() { 141 @Override 142 public void checkClientTrusted(X509Certificate[] xcs, String string) { 143 } 144 145 @Override 146 public void checkServerTrusted(X509Certificate[] xcs, String string) { 147 } 148 149 @Override 150 public X509Certificate[] getAcceptedIssuers() { 151 return null; 152 } 153 }; 154 155 SSLContext sslContext = null; 156 try { 157 sslContext = SSLContext.getInstance("TLS"); 158 } catch (NoSuchAlgorithmException e1) { 159 e1.printStackTrace(); 160 } 161 162 try { 163 sslContext.init(null, new TrustManager[] { x509mgr }, null); 164 } catch (KeyManagementException e) { 165 e.printStackTrace(); 166 } 167 168 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 169 170 HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { 171 @Override 172 public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { 173 if (executionCount >= 5) {// 如果已经重试了5次,就放弃 174 return false; 175 } 176 if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 177 return true; 178 } 179 if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 180 return false; 181 } 182 if (exception instanceof InterruptedIOException) {// 超时 183 return false; 184 } 185 if (exception instanceof UnknownHostException) {// 目标服务器不可达 186 return false; 187 } 188 if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 189 return false; 190 } 191 if (exception instanceof SSLException) {// ssl握手异常 192 return false; 193 } 194 // 2016-03-09针对broken pipe的问题做处理 195 if (exception instanceof SocketException) { 196 return true; 197 } 198 199 HttpClientContext clientContext = HttpClientContext.adapt(context); 200 HttpRequest request = clientContext.getRequest(); 201 // 如果请求是幂等的,就再次尝试 202 if (!(request instanceof HttpEntityEnclosingRequest)) { 203 return true; 204 } 205 return false; 206 } 207 }; 208 DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy() { 209 public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) { 210 boolean isRedirect = false; 211 try { 212 isRedirect = super.isRedirected(request, response, context); 213 } catch (ProtocolException e) { 214 e.printStackTrace(); 215 } 216 if (!isRedirect) { 217 int responseCode = response.getStatusLine().getStatusCode(); 218 if (responseCode == 301 || responseCode == 302) { 219 return true; 220 } 221 } 222 return isRedirect; 223 } 224 225 @Override 226 protected URI createLocationURI(String location) throws ProtocolException { 227 location = location.replace("|", "%7C"); 228 return super.createLocationURI(location); 229 } 230 }; 231 232 HttpClientBuilder httpClientBuilder = HttpClients.custom(); 233 httpClientBuilder.setDefaultRequestConfig(requestConfig); 234 if (route > 0 && maxTotal > 0) { 235 PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); 236 connManager.setDefaultMaxPerRoute(route); 237 connManager.setMaxTotal(maxTotal); 238 httpClientBuilder.setConnectionManager(connManager); 239 } 240 241 httpClientBuilder.setSSLSocketFactory(sslsf); 242 httpClientBuilder.setDefaultCookieStore(cookieStore); 243 httpClientBuilder.setRedirectStrategy(redirectStrategy); 244 httpClientBuilder.setRetryHandler(httpRequestRetryHandler); 245 httpClient = httpClientBuilder.build(); 246 } 247 public Response sendRequest(Request request) throws Exception { 248 // request.setHeader("Accept", 249 // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 250 // request.setHeader("Accept-Encoding", "gzip, deflate"); 251 if (request.getHeader("User-Agent") == null) { 252 request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0"); 253 } 254 request.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"); 255 request.setHeader("Connection", "keep-alive"); 256 257 // logger.debug("发送请求:" + request); 258 259 String method = request.getProperty("method").toLowerCase(); 260 String url = request.getProperty("url"); 261 Map<String, String> headers = request.getHeaders(); 262 Map<String, String> params = request.getParams(); 263 List<NameValuePair> formParams = new ArrayList<NameValuePair>(); 264 if (params != null && params.size() != 0) { 265 formParams = new ArrayList<NameValuePair>(); 266 for (Entry<String, String> entry : params.entrySet()) { 267 formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 268 } 269 } 270 271 Response response = null; 272 if ("post".equals(method)) { 273 byte[] postData = request.getPostData(); 274 if (postData != null) { 275 response = post(url, postData, headers); 276 } else { 277 response = post(url, formParams, headers); 278 } 279 } else if ("get".equals(method)) { 280 response = get(url, formParams, headers); 281 } 282 return response; 283 } 284 285 /** 286 * Get请求 287 * 288 * @param url 289 * @param params 290 * @return 291 */ 292 public Response get(String url, List<NameValuePair> params, Map<String, String> headers) { 293 Response response = new Response(); 294 try { 295 // Get请求 296 HttpGet httpGet = new HttpGet(url); 297 298 String encoding = "utf-8"; 299 300 // 设置头 301 if (headers != null && headers.size() != 0) { 302 for (Entry<String, String> entry : headers.entrySet()) { 303 httpGet.setHeader(entry.getKey(), entry.getValue()); 304 } 305 306 String contentType = headers.get("Content-Type"); 307 if (StringUtils.isNotBlank(contentType)) { 308 if (matcher(contentType, "(charset)\\s?=\\s?(gbk)")) { 309 encoding = "gbk"; 310 } else if (matcher(contentType, "(charset)\\s?=\\s?(gb2312)")) { 311 encoding = "gb2312"; 312 } 313 } 314 } 315 316 // 设置参数,如果url上已经有了问号,就不附加参数 317 if (params != null && params.size() > 0) { 318 if (httpGet.getURI().toString().indexOf("?") == -1) { 319 String str = EntityUtils.toString(new UrlEncodedFormEntity(params, encoding)); 320 httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + str)); 321 } else { 322 String str = EntityUtils.toString(new UrlEncodedFormEntity(params, encoding)); 323 httpGet.setURI(new URI(httpGet.getURI().toString() + "&" + str)); 324 } 325 } 326 327 // 发送请求 328 CloseableHttpResponse httpResponse = httpClient.execute(httpGet); 329 330 try { 331 int statusCode = httpResponse.getStatusLine().getStatusCode(); 332 response.setStatusCode(statusCode); 333 ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 334 // 获取返回数据 335 HttpEntity entity = httpResponse.getEntity(); 336 337 Header[] responseHeaders = httpResponse.getAllHeaders(); 338 for (Header header : responseHeaders) { 339 response.setHeader(header.getName(), header.getValue()); 340 } 341 342 Header header = entity.getContentEncoding(); 343 if (header != null && header.getValue().toLowerCase().equals("gzip")) { 344 byte[] bytes = IOUtils.toByteArray(new GZIPInputStream(entity.getContent())); 345 response.setContent(bytes); 346 } else { 347 byte[] bytes = getData(entity); 348 response.setContent(bytes); 349 } 350 return response; 351 } finally { 352 httpResponse.close(); 353 } 354 } catch (ConnectTimeoutException e) { 355 } catch (HttpHostConnectException e) { 356 } catch (ParseException e) { 357 } catch (UnsupportedEncodingException e) { 358 } catch (IOException e) { 359 } catch (URISyntaxException e) { 360 } catch (Exception e) { 361 } 362 return null; 363 } 364 365 /** 366 * // Post请求 367 * 368 * @param url 369 * @param params 370 * @return 371 */ 372 public Response post(String url, byte[] data, Map<String, String> headers) { 373 Response response = new Response(); 374 try { 375 // Post请求 376 HttpPost httpPost = new HttpPost(url); 377 // 设置头 378 if (headers != null && headers.size() != 0) { 379 for (Entry<String, String> entry : headers.entrySet()) { 380 httpPost.setHeader(entry.getKey(), entry.getValue()); 381 } 382 } 383 384 // 设置参数 385 httpPost.setEntity(new ByteArrayEntity(data)); 386 387 // 发送请求 388 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); 389 390 try { 391 int statusCode = httpResponse.getStatusLine().getStatusCode(); 392 response.setStatusCode(statusCode); 393 394 // 获取返回数据 395 HttpEntity entity = httpResponse.getEntity(); 396 397 Header header = entity.getContentEncoding(); 398 if (header != null && header.getValue().toLowerCase().equals("gzip")) { 399 byte[] bytes = IOUtils.toByteArray(new GZIPInputStream(entity.getContent())); 400 response.setContent(bytes); 401 } else { 402 byte[] bytes = EntityUtils.toByteArray(entity); 403 response.setContent(bytes); 404 } 405 406 return response; 407 } finally { 408 httpResponse.close(); 409 } 410 } catch (ConnectTimeoutException e) { 411 } catch (HttpHostConnectException e) { 412 } catch (UnsupportedEncodingException e) { 413 } catch (ClientProtocolException e) { 414 } catch (ParseException e) { 415 } catch (IOException e) { 416 } catch (Exception e) { 417 } 418 return null; 419 } 420 private byte[] getData(HttpEntity entity) throws IOException { 421 if (entity == null) { 422 throw new IllegalArgumentException("HTTP entity may not be null"); 423 } 424 InputStream inputStream = entity.getContent(); 425 if (inputStream == null) { 426 return null; 427 } 428 try { 429 if (entity.getContentLength() > Integer.MAX_VALUE) { 430 throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); 431 } 432 int i = (int) entity.getContentLength(); 433 if (i < 0) { 434 i = 4096; 435 } 436 437 ByteArrayBuffer buffer = new ByteArrayBuffer(i); 438 byte[] tmp = new byte[1024]; 439 int l = -1; 440 try { 441 while ((l = inputStream.read(tmp)) != -1) { 442 buffer.append(tmp, 0, l); 443 } 444 } catch (EOFException e) { 445 buffer.clear(); 446 // 针对于以没有结束符的做fix处理,减小缓存,并进行异常处理,忽略最后不能获取的数据 447 tmp = new byte[32]; 448 try { 449 while ((l = inputStream.read(tmp)) != 1) { 450 buffer.append(tmp, 0, l); 451 } 452 } catch (EOFException e2) { 453 } 454 455 } 456 // TODO 查明具体没有返回的原因 457 byte[] byteArray = buffer.toByteArray(); 458 if (byteArray == null || byteArray.length == 0) { 459 return buffer.buffer(); 460 } 461 return byteArray; 462 } finally { 463 inputStream.close(); 464 } 465 } 466 /** 467 * // Post请求 468 * 469 * @param url 470 * @param params 471 * @return 472 */ 473 public Response post(String url, List<NameValuePair> params, Map<String, String> headers) { 474 Response response = new Response(); 475 try { 476 // Post请求 477 HttpPost httpPost = new HttpPost(url); 478 479 String encoding = "utf-8"; 480 481 // 设置头 482 if (headers != null && headers.size() != 0) { 483 for (Entry<String, String> entry : headers.entrySet()) { 484 httpPost.setHeader(entry.getKey(), entry.getValue()); 485 } 486 487 String contentType = headers.get("Content-Type"); 488 if (StringUtils.isNotBlank(contentType)) { 489 if (matcher(contentType, "(charset)\\s?=\\s?(gbk)")) { 490 encoding = "gbk"; 491 } else if (matcher(contentType, "(charset)\\s?=\\s?(gb2312)")) { 492 encoding = "gb2312"; 493 } 494 } 495 } 496 497 // 设置参数 498 if (params != null && params.size() > 0) { 499 httpPost.setEntity(new UrlEncodedFormEntity(params, encoding)); 500 } 501 // 发送请求 502 CloseableHttpResponse httpResponse = httpClient.execute(httpPost); 503 504 try { 505 int statusCode = httpResponse.getStatusLine().getStatusCode(); 506 response.setStatusCode(statusCode); 507 508 // 获取返回数据 509 HttpEntity entity = httpResponse.getEntity(); 510 511 Header header = entity.getContentEncoding(); 512 if (header != null && header.getValue().toLowerCase().equals("gzip")) { 513 byte[] data = IOUtils.toByteArray(new GZIPInputStream(entity.getContent())); 514 response.setContent(data); 515 } else { 516 byte[] data = getData(entity); 517 response.setContent(data); 518 } 519 520 return response; 521 } finally { 522 httpResponse.close(); 523 } 524 } catch (ConnectTimeoutException e) { 525 } catch (HttpHostConnectException e) { 526 } catch (UnsupportedEncodingException e) { 527 } catch (ClientProtocolException e) { 528 } catch (ParseException e) { 529 } catch (IOException e) { 530 } catch (Exception e) { 531 } 532 return null; 533 } 534 535 /** 536 * 获取Response内容字符集 537 * 538 * @param response 539 * @return 540 */ 541 public String getContentCharset(HttpResponse response) { 542 String charset = "ISO_8859-1"; 543 Header header = response.getEntity().getContentType(); 544 if (header != null) { 545 String s = header.getValue(); 546 if (matcher(s, "(charset)\\s?=\\s?(utf-?8)")) { 547 charset = "utf-8"; 548 } else if (matcher(s, "(charset)\\s?=\\s?(gbk)")) { 549 charset = "gbk"; 550 } else if (matcher(s, "(charset)\\s?=\\s?(gb2312)")) { 551 charset = "gb2312"; 552 } 553 } 554 555 Header encoding = response.getEntity().getContentEncoding(); 556 557 return charset; 558 } 559 560 /** 561 * 正则匹配 562 * 563 * @param s 564 * @param pattern 565 * @return 566 */ 567 private boolean matcher(String s, String pattern) { 568 Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE + Pattern.UNICODE_CASE); 569 Matcher matcher = p.matcher(s); 570 if (matcher.find()) { 571 return true; 572 } else { 573 return false; 574 } 575 } 576 577 public Integer getConnectTimeout() { 578 return connectTimeout; 579 } 580 581 public void setConnectTimeout(Integer connectTimeout) { 582 this.connectTimeout = connectTimeout; 583 } 584 585 public Integer getSocketTimeout() { 586 return socketTimeout; 587 } 588 589 public void setSocketTimeout(Integer socketTimeout) { 590 this.socketTimeout = socketTimeout; 591 } 592 593 public CloseableHttpClient getHttpClient() { 594 return httpClient; 595 } 596 597 public void setHttpClient(CloseableHttpClient httpClient) { 598 this.httpClient = httpClient; 599 } 600 601 public CookieStore getCookieStore() { 602 return cookieStore; 603 } 604 605 public void setCookieStore(CookieStore cookieStore) { 606 for(Cookie cookie:cookieStore.getCookies()){ 607 this.cookieStore.addCookie(cookie); 608 } 609 } 610 611 }
六,补充类StringUtils
1 package com.http; 2 3 public class StringUtils { 4 5 /** 6 * Unicode 转化成中文 7 * 8 * @param utfString 9 * @return 10 */ 11 public static String decodeUnicode(String theString) { 12 char aChar; 13 int len = theString.length(); 14 StringBuffer outBuffer = new StringBuffer(len); 15 for (int x = 0; x < len;) { 16 aChar = theString.charAt(x++); 17 if (aChar == '\\') { 18 aChar = theString.charAt(x++); 19 if (aChar == 'u') { 20 // Read the xxxx 21 int value = 0; 22 for (int i = 0; i < 4; i++) { 23 aChar = theString.charAt(x++); 24 switch (aChar) { 25 case '0': 26 case '1': 27 case '2': 28 case '3': 29 case '4': 30 case '5': 31 case '6': 32 case '7': 33 case '8': 34 case '9': 35 value = (value << 4) + aChar - '0'; 36 break; 37 case 'a': 38 case 'b': 39 case 'c': 40 case 'd': 41 case 'e': 42 case 'f': 43 value = (value << 4) + 10 + aChar - 'a'; 44 break; 45 case 'A': 46 case 'B': 47 case 'C': 48 case 'D': 49 case 'E': 50 case 'F': 51 value = (value << 4) + 10 + aChar - 'A'; 52 break; 53 default: 54 throw new IllegalArgumentException( 55 "Malformed \\uxxxx encoding."); 56 } 57 58 } 59 outBuffer.append((char) value); 60 } else { 61 if (aChar == 't') 62 aChar = '\t'; 63 else if (aChar == 'r') 64 aChar = '\r'; 65 else if (aChar == 'n') 66 aChar = '\n'; 67 else if (aChar == 'f') 68 aChar = '\f'; 69 outBuffer.append(aChar); 70 } 71 } else 72 outBuffer.append(aChar); 73 } 74 return outBuffer.toString(); 75 } 76 }
七,补充类BaiduMapProxyService
1 package com.http; 2 3 4 5 /** 6 * 使用代理 请求会经过代理 7 * title:百度地图服务类 <br> 8 * 版权: Copyright (c) 2011-2016<br> 9 * 10 * @author:Administrator<br> 11 * @date:Apr 7, 2016<br> 12 */ 13 public class BaiduMapProxyService { 14 15 /** 16 * 代理发送请求 17 */ 18 private HttpClientUtil httpClientUtil=new HttpClientUtil("127.0.0.1",8888); 19 20 public String insertLocation(String title, String longitude, 21 String latitude, String address) { 22 23 //插入数据接口 24 String url = "http://api.map.baidu.com/geodata/v3/poi/create"; 25 26 Request request=new Request(); 27 //数据 28 request.setProperty("url", url); 29 request.setProperty("method", "post"); 30 31 //我自己的百度云数据库名称 32 request.setParam("geotable_id", "137287"); 33 request.setParam("ak", "GShGXR4uNroTq4mzqsf1v7h3VgsC3aIk"); 34 request.setParam("latitude", latitude); 35 request.setParam("longitude", longitude); 36 request.setParam("address", address); 37 request.setParam("coord_type", "3"); 38 39 request.setParam("title", title); 40 41 Response response; 42 try { 43 response = httpClientUtil.sendRequest(request); 44 if(response==null||response.getStatusCode()!=200){ 45 return null; 46 } 47 String content =response.getContentString("utf-8"); 48 System.out.println("返回的数据是:"+content); 49 return content; 50 } catch (Exception e) { 51 // TODO Auto-generated catch block 52 e.printStackTrace(); 53 } 54 55 return null; 56 57 } 58 59 /** 60 * 根据经纬度查周边学校半径500米 61 * 62 * @return 63 */ 64 public String findNearBySchool(String longitude, String latitude) { 65 String url = "http://api.map.baidu.com/geosearch/v3/nearby?geotable_id=137287&ak=GShGXR4uNroTq4mzqsf1v7h3VgsC3aIk&radius=500&location=" 66 + longitude + "," + latitude; 67 68 69 70 Request request=new Request(); 71 request.setProperty("url", url); 72 request.setProperty("method", "get"); 73 74 Response response=new Response(); 75 76 try { 77 response = httpClientUtil.sendRequest(request); 78 if(response==null||response.getStatusCode()!=200){ 79 return null; 80 } 81 82 String content =response.getContentString("utf-8"); 83 System.out.println("返回数据:"+content); 84 return content; 85 } catch (Exception e) { 86 // TODO Auto-generated catch block 87 e.printStackTrace(); 88 } 89 return null; 90 91 } 92 }
相关文章推荐
- http接口开发与调用案例
- httpclient案例一(调用识别接口)
- HttpClient Get/Post方式调用Http接口
- HttpKit 基于Jfianl 调用第三方接口案例
- SpringMVC,MyBatis项目中兼容Oracle和MySql的解决方案及其项目环境搭建配置、web项目中的单元测试写法、HttpClient调用post请求等案例
- apache httpclient HTTPS发送JSON调用接口实例
- java 调用接口 HttpClient
- httpclient 调用第三方接口
- HttpClient调用Web Api接口帮助类
- java后台通过HttpClient调用第三方接口
- HttpClient调用其他接口
- restful接口客户端和服务端开发,HttpURLConnection,HttpClient,post ,get方式调用
- http请求,HttpClient,调用短信接口
- SAP中用json数据格式调用http接口发送短信邮件案例
- java HttpClient get post请求 调用接口
- Java HttpClient在外围接口调用实例
- httpclient http接口调用
- Spring mvc REST风格对外接口,HttpClient调用
- httpClient发送get请求调用接口
- httpClient 接口调用