JAVA httpclient 请求最佳实现

以下会依次列举常见的几种请求类型 : get , post param , post json , post file

GET

/*** get类型的* * @param url* @throws ClientProtocolException* @throws IOException*/
public static void testGet(String url) throws ClientProtocolException, IOException {// 设置超时时间,单位是秒RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setConnectionRequestTimeout(3000).build();CloseableHttpClient httpclient = HttpClients.createDefault();try {HttpGet httpget = new HttpGet(url);httpget.setConfig(defaultRequestConfig);ResponseHandler<String> responseHandler = new ResponseHandler<String>() {public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {int status = response.getStatusLine().getStatusCode();if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();return entity != null ? EntityUtils.toString(entity) : null;} else {throw new ClientProtocolException("Unexpected response status: " + status);}}};String responseBody = httpclient.execute(httpget, responseHandler);System.out.println(responseBody);} finally {httpclient.close();}
}

POST 参数

/*** form类型的,传参数* * @param url* @param map 参数* @throws ClientProtocolException* @throws IOException*/
public static void testPostParam(String url,Map<String,String> map) throws ClientProtocolException, IOException {// 设置超时时间RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setConnectionRequestTimeout(3000).build();CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();httpClient = HttpClients.createDefault();HttpPost post = new HttpPost("http://httpbin.org/post");post.setConfig(defaultRequestConfig);// 传参数List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();for(Entry<String,string> entry: map.entrySet()){list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}HttpEntity ent = new UrlEncodedFormEntity(list, "UTF-8");post.setEntity(ent);ResponseHandler<String> responseHandler = new ResponseHandler<String>() {public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {int status = response.getStatusLine().getStatusCode();System.out.println(response.getEntity().toString());if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();return entity != null ? EntityUtils.toString(entity) : null;} else {throw new ClientProtocolException("Unexpected response status: " + status);}}};System.out.println(httpClient.execute(post, responseHandler));
}

POST JSON

/*** post json* * @param url 请求地址* @param jsonStr 请求json字符串* @throws ClientProtocolException* @throws IOException*/
public static void testPostJson(String url,String jsonStr) throws ClientProtocolException, IOException {// 设置超时时间RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setConnectionRequestTimeout(3000).build();CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();httpClient = HttpClients.createDefault();HttpPost post = new HttpPost(url);post.setConfig(defaultRequestConfig);// 传json字符串 "{\"key\":\"value\"}"StringEntity stringEntity = new StringEntity(jsonStr);stringEntity.setContentType("text/json");stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));post.setEntity(stringEntity);ResponseHandler<String> responseHandler = new ResponseHandler<String>() {public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {int status = response.getStatusLine().getStatusCode();if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();return entity != null ? EntityUtils.toString(entity) : null;} else {throw new ClientProtocolException("Unexpected response status: " + status);}}};System.out.println(httpClient.execute(post, responseHandler));
}

POST FILE

/*** 上传文件* @param url 上传接口地址* @param filePath* @param fileName* @throws ClientProtocolException* @throws IOException*/
public static void testPostFile(String url,String filePath,string fileName) throws ClientProtocolException, IOException {RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(3000).setConnectionRequestTimeout(3000).build();CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();httpClient = HttpClients.createDefault();HttpPost post = new HttpPost(url);// 设置超时时间post.setConfig(defaultRequestConfig);// 传文件MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);builder.addTextBody("name", "test");builder.addBinaryBody("file", new File(filePath), ContentType.DEFAULT_BINARY,fileName);post.setEntity(builder.build());ResponseHandler<String> responseHandler = new ResponseHandler<String>() {public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {int status = response.getStatusLine().getStatusCode();if (status >= 200 && status < 300) {HttpEntity entity = response.getEntity();return entity != null ? EntityUtils.toString(entity) : null;} else {throw new ClientProtocolException("Unexpected response status: " + status);}}};System.out.println(httpClient.execute(post, responseHandler));
}

利用HttpClient4,实现get,post 参数,post json,post file相关推荐

  1. Gson应用:利用map和list来拼装Json消息

    Gson应用:利用map和list来拼装Json消息 1 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import ja ...

  2. GoJS超详细入门(插件使用无非:引包、初始化、配参数(json)、引数据(json)四步)...

    GoJS超详细入门(插件使用无非:引包.初始化.配参数(json).引数据(json)四步) 一.总结 一句话总结:插件使用无非:引包.初始化.配参数(json).引数据(json)四步. 1.goj ...

  3. go系列之利用Gin框架获取form参数

    利用Gin框架获取form参数 除了通过URL查询参数提交数据到服务器外,常用的还有通过Form表单的方式.Form表单相比URL查询参数,用户体验好,可以承载更多的数据,尤其是文件上传,所以也更为方 ...

  4. 将表单中查询参数转换为json

    <script type="text/javascript">                 //扩展了jquery的方法,将表单中的参数转换为json        ...

  5. mysql jsp分页技术_一个非常简单的分页技术MYSQL JSP 利用了mysql的LIMIT参数

    一个非常简单的分页技术MYSQL JSP 利用了mysql的LIMIT参数 优点:1自己想出来的 2利用了MYSQL 数据库的本身 LIMIT 缺点:现在仅仅实现了 下一个页面功能 <% int ...

  6. 利用jquery写的从后台获取json数据以表格显示,并带翻页功能.里面包含模式窗口等功能...

    利用jquery写的从后台获取json数据,以表格显示,并带翻页功能 里面包含模式窗口等功能 大家看例子就懂了 下面是效果图: http://www.jm47.com/project/3001.asp ...

  7. matlab 非线性电感,基于Matlab/Simulink利用动态和静态电感等磁参数建立了一种开关磁阻电机的非线性磁参数模型...

    基于动.静态电感特性的开关磁阻电机非线性磁参数模型 蒋涛 (北京航空航天大学,北京100191) 摘要:基于Matlab/Simulink.利用动态和静态电感等磁参数建立了一种开关磁阻电机的非线性磁参 ...

  8. 将url参数转为json对象

    /*** 将url参数转为json对象** @param str* @returns {{}}*/ function parseQueryString(str){arr = [],length = 0 ...

  9. http POST请求键值对参数以及json参数

    在使用post进行http请求时有2种参数类型,要根据接口切换不同的参数格式 键值对格式参数一般表现为:username=123&password=123 json格式参数一般表现为:{&qu ...

  10. 利用matlab工具箱的pid参数科学整定方法

    声明 这篇文章目前仅对电机调速有效,暂时不知道对调整姿态这样的pid是否可以有同样的效果.如果是SISO,我的感觉是可以的,可以尝试方波信号而不是简单的阶跃. 采集数据 给电机提供一个单位阶跃输入(固 ...

最新文章

  1. Mybatis传递多个参数的4种方式
  2. arcgisserver修改服务器地址,ArcGIS for Server默认端口6080修改
  3. 彻底给你讲清楚分布式事务原理
  4. 人体姿态估计(Human Pose Estimation)技巧方法汇总
  5. 物联网激荡MEMS传感器浪潮
  6. hitTest和pointInside如何响应用户点击事件
  7. 腾讯十周年,看看你的QQ是什么时候注册的?
  8. 『转载』在vs2008(2005)winform中,打开office文档
  9. jmeter HTTPS和HTTP的区别
  10. Java-Jdbc,JDBC连接Oracle11g实例:
  11. vss团队开发工具使用(个人学习心得)
  12. @sql 单元测试_SQL单元测试最佳实践
  13. 在 WPF 程序中使用矢量图
  14. 调用阿里云语音识别接口
  15. clickhouse ARRAY JOIN函数
  16. Intro.js 分步向导插件使用方法
  17. 机器学习Machine Learning:特征选择Feature Selection 与 数据降维Dimension Reduction的区别?
  18. 试发贴:央视《焦点访谈》曝光淘宝网纵容售假
  19. 传奇单机架设教程 小白也能开传奇
  20. Ubuntu安装QQ、VM、Chrom软件

热门文章

  1. 计算机网络-----IP地址分配
  2. 2011年12月13日 timeout 与 refused windows clipbrd
  3. 高中计算机数据的基本特征,高一信息技术《信息与信息的基本特征》教案
  4. MapServer教程
  5. Python爬虫工具
  6. Struts2通配符问题
  7. win7计算机管理没有用户模块,Win7系统安装“ipx协议”提示“找不到相应的模块”如何解决...
  8. 解决局域网共享文件时提示“没有权限访问,请与网络管理员联系请求访问权限“
  9. 软件工程导论01-概论
  10. java 硬盘序列号_如何使用Java获取硬盘序列号?