httpclient常用方法封装
来源:互联网 发布:apache beam 实时流 编辑:程序博客网 时间:2024/05/17 08:49
项目依赖
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpasyncclient</artifactId> <version>4.1.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.35</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency> </dependencies>
模拟get请求
public static String get(String url, Map<String, String> params) { String respString = ""; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); try { CloseableHttpResponse response = httpclient.execute(httpget); HttpEntity httpEntity = response.getEntity(); respString = EntityUtils.toString(httpEntity); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { } } return respString; }
模拟post请求
public static String postForm(String url, Map<String, String> form) { String respString = ""; List<NameValuePair> formParams = new ArrayList<>(); Set<Map.Entry<String, String>> entries = form.entrySet(); Iterator<Map.Entry<String, String>> it = entries.iterator(); while (it.hasNext()) { Map.Entry<String, String> next = it.next(); String key = next.getKey(); String value = next.getValue(); formParams.add(new BasicNameValuePair(key, value)); } CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8"); HttpPost request = new HttpPost(url); request.setEntity(entity); CloseableHttpResponse response = httpclient.execute(request); request.abort();//释放post请求 if (response.getStatusLine().getStatusCode() == 302) { String locationUrl = response.getLastHeader("Location").getValue(); respString = get(locationUrl, null);//跳转到重定向的url } else if (response.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = response.getEntity(); respString = EntityUtils.toString(httpEntity); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { } } return respString; }
模拟getJson请求
public static String get(String url, Map<String, String> params) { String respString = ""; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); try { CloseableHttpResponse response = httpclient.execute(httpget); HttpEntity httpEntity = response.getEntity(); respString = EntityUtils.toString(httpEntity); } catch (IOException e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { } } return respString; }
模拟postJson请求
public static String postJson(String url, String json) { String resultJson = ""; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost(url); CloseableHttpResponse response = null; try { StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("UTF-8"); httppost.setEntity(entity); response = httpclient.execute(httppost); HttpEntity result = response.getEntity(); resultJson = EntityUtils.toString(result, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { if (response != null) { try { response.close(); } catch (IOException e) { } } } return resultJson; }
模拟异步postJson请求
public static String postJsonAsync(String url, String json, Integer timeOut, Class<? extends FutureCallback<HttpResponse>> clazz) { if (timeOut == null || timeOut < 0) { timeOut = 5000; } String resultJson = ""; // 创建默认的httpClient实例. final CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault(); // 创建httppost httpclient.start(); FutureCallback<HttpResponse> futureCallback = null; try { Constructor<? extends FutureCallback<HttpResponse>> declaredConstructor = clazz.getDeclaredConstructor(CloseableHttpAsyncClient.class); futureCallback = declaredConstructor.newInstance(httpclient); } catch (NoSuchMethodException e) { } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } final HttpPost httppost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(2000).build();// 设置请求和传输超时时间 httppost.setConfig(requestConfig); try { StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httppost.setEntity(entity); httpclient.execute(httppost, futureCallback); } catch (Exception e) { e.printStackTrace(); } finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultJson; }
模拟使用异步postJson
public static void main(String[] args) { postJsonAsync("url", "{'a':1}", 50, CallBack.class); } static class CallBack implements FutureCallback<HttpResponse> { private CloseableHttpAsyncClient httpclient; public CallBack(CloseableHttpAsyncClient httpclient) { this.httpclient = httpclient; } @Override public void completed(HttpResponse response) { HttpEntity result = response.getEntity(); try { String resultJson = EntityUtils.toString(result, "UTF-8"); System.out.println(resultJson); } catch (IOException e) { e.printStackTrace(); } } @Override public void failed(Exception ex) { } @Override public void cancelled() { } }
阅读全文
1 0
- httpclient常用方法封装
- 对HttpClient方法的封装
- 对HttpClient的一些封装方法
- HttpClient API常用方法解释
- JDBC常用方法封装
- Selenium2 常用方法封装
- js 常用封装方法
- 自己常用方法封装
- 常用的封装方法
- iOS常用封装方法
- IOS 常用方法封装
- selenium封装常用方法
- Javascript封装常用方法
- extjs常用方法封装
- Selenium2常用方法封装
- jedis常用方法封装
- HttpClient封装
- spring+httpclient完美集成,封装常用客户端工具类
- R语言读CSV、txt文件方式以及read.table read.csv 和readr(大数据读取包)
- 将Linux命令的结果作为下一个命令的参数
- C语言通讯录(利用数组实现)
- 51nod 1090 & 1267 【二分简单题】
- 框架整合____Spring整合Mybatis(主流,最精简整合方式,)
- httpclient常用方法封装
- 求N!的长度【数学】 51nod 1058 1130
- centos下安装nginx
- PHP 运用 Redis 构建高性能的实时搜索
- opengl光照之漫反射逐顶点渲染与逐像素渲染
- Codeforces Round #406 (Div. 2)
- Hibernate学习笔记(二)
- Codeforces Round #407 (Div. 2)
- python 中 类 子类 属性 方法 对象 self 理解