使用HttpClient模拟HTTP发送POST或GET请求
在Java开发中,服务与服务之间进行调用,需要使用HttpClient发送HTTP请求,以下是使用Java实现模拟HTTP发送POST或GET请求的代码
1、pom.xml中导入HTTP依赖
<!-- HTTP请求依赖 --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><!-- json依赖 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>
2、发送Post或get请求
需要传参数时注意:文本参数用StringEntity,参数放入json对象里面,文件参数用MultipartEntityBuilder
package com.dascom.smallroutine.utils;
import java.io.IOException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;public class HttpClientUtil {//日志输出private static Logger logger = LogManager.getLogger(HttpClientUtil.class);/*** 发送get请求 调用这个方法* @param url* @return str //返回请求的内容* @throws Exception*/public static String doGet(String url){// 创建Httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();;String returnValue = null;// 创建http GET请求HttpGet httpGet = new HttpGet(url);CloseableHttpResponse response = null;try {//执行请求response = httpClient.execute(httpGet);//判断返回状态是否为200if(response.getStatusLine().getStatusCode() == 200) {//请求体内容returnValue = EntityUtils.toString(response.getEntity(), "UTF-8");return returnValue;}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (response != null) {try {response.close();} catch (IOException e) {logger.error("response关闭失败!");e.printStackTrace();}}try {httpClient.close();} catch (IOException e) {logger.error("httpClient关闭失败!");e.printStackTrace();}}return returnValue;}/*** 发送Post请求 调用这个方法 带json参数* @param url 要请求的地址* @param json 要发送的json格式数据* @return 返回的数据*/public static String doPostWithJson(String url,JSONObject json){String returnValue = null;CloseableHttpClient httpclient = null;ResponseHandler<String> responseHandler = new BasicResponseHandler();try {//创建httpclient对象httpclient = HttpClients.createDefault();//创建http POST请求HttpPost httpPost = new HttpPost(url);//文本参数用StringEntity,文件参数用MultipartEntityBuilderStringEntity requestEntity = new StringEntity(json.toJSONString(),"utf-8");requestEntity.setContentEncoding("UTF-8");httpPost.setHeader("Content-type","application/json");//请求头httpPost.setEntity(requestEntity);//发送请求,获取返回值returnValue = httpclient.execute(httpPost,responseHandler);}catch (Exception e) {logger.error("发送post请求失败!"+e.getMessage());}finally {try {httpclient.close();} catch (IOException e) {logger.error("httpclient关闭失败!"+e.getMessage());}}return returnValue;}
}
3、测试类
public class Test {public static void main(String[] args) {//GET请求访问HttpClientUtil.doGet("http://baidu.com");//POST请求访问JSONObject json = new JSONObject();json.put("data", "成功");//参数HttpClientUtil.doPostWithJson("http://baidu.com", json);}
}
如果要请求有文件参数接口,例子如下
代码实现
package com.example.demo.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
@RestController
@RequestMapping("/v1.0")
public class PrintController {//日志输出private static Logger logger = LogManager.getLogger(PrintController.class);@RequestMapping(value="/monitprint",method=RequestMethod.POST,produces ="application/json;charset=utf-8")public JSONObject monitoringPrint(@RequestParam(required=false) MultipartFile file) { //POST请求访问JSONObject json = new JSONObject(); String s=PrintController.doPostWithJson("http://127.0.0.1:20173/v2.0/print/0015CA7350020300", file); if(s!=null&&!"".equals(s)) {json.put("data", "访问成功");}else{json.put("data", "访问失败");} return json;}/*** 发送Post请求 调用这个方法 带json参数* @param url 要请求的地址* @param json 要发送的json格式数据* @return 返回的数据*/public static String doPostWithJson(String url,MultipartFile Mfile){String returnValue = null;CloseableHttpClient httpclient = null;ResponseHandler<String> responseHandler = new BasicResponseHandler();try {//创建httpclient对象httpclient = HttpClients.createDefault();//创建http POST请求HttpPost httpPost = new HttpPost(url);//文本参数用StringEntity,文件参数用MultipartEntityBuilderMultipartEntityBuilder builder = MultipartEntityBuilder.create();//MultipartFile转FileFile file=multipartFileToFile(Mfile);builder.addBinaryBody("file", file);httpPost.setHeader("File-Type","pdf");//请求头HttpEntity reqEntity = builder.build();httpPost.setEntity(reqEntity);//发送请求,获取返回值returnValue = httpclient.execute(httpPost,responseHandler);}catch (Exception e) {logger.error("发送post请求失败!"+e.getMessage());}finally {try {httpclient.close();} catch (IOException e) {logger.error("httpclient关闭失败!"+e.getMessage());}}return returnValue;}/*** MultipartFile 转 File* @param file* @throws Exception*/public static File multipartFileToFile(MultipartFile file) throws Exception {File toFile = null;if (file.equals("") || file.getSize() <= 0) {file = null;} else {InputStream ins = null;ins = file.getInputStream();toFile = new File(file.getOriginalFilename());inputStreamToFile(ins, toFile);ins.close();}return toFile;}/*** 获取流文件* @param ins* @param file*/private static void inputStreamToFile(InputStream ins, File file) {try {OutputStream os = new FileOutputStream(file);int bytesRead = 0;byte[] buffer = new byte[8192];while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {os.write(buffer, 0, bytesRead);}os.close();ins.close();} catch (Exception e) {e.printStackTrace();}}
}
4、x-www-form-urlencoded类型的参数
实现代码
public class Test {public static void main(String[] args) {List<NameValuePair> params = new ArrayList<NameValuePair>();NameValuePair pair = new BasicNameValuePair("grant_type", "client_credentials");NameValuePair pair2 = new BasicNameValuePair("app_key", "YLbbATeusEJbPCZiZ1n6paICffMu");NameValuePair pair3 = new BasicNameValuePair("app_secret", "oR93ABEWRDAIldXpZ6W4EbOvmV8NfKiMPl3OcO8U41yjeXNGaNNgr1xC4DGe5");params.add(pair);params.add(pair2);params.add(pair3);String postForString = postWithParamsForString("https://openapi.italent.cn/token", params);System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>post:"+postForString);}
}
//POST请求
public static String postWithParamsForString(String url, List<NameValuePair> params){HttpClient client = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);String s = "";try {httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");HttpResponse response = client.execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if(statusCode==200){HttpEntity entity = response.getEntity();s = EntityUtils.toString(entity);}} catch (IOException e) {e.printStackTrace();}return s;}
欢迎大家阅读,本人见识有限,写的博客难免有错误或者疏忽的地方,还望各位大佬指点,在此表示感谢。
使用HttpClient模拟HTTP发送POST或GET请求相关推荐
- C#模拟http 发送post或get请求
C#模拟http 发送post或get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 2 ...
- HttpClient 同时支持发送http及htpps请求
HttpClient简述: HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包.HTTP Client和浏 ...
- java爬虫模拟post请求_java爬虫之使用HttpClient模拟浏览器发送请求方法详解
0. 摘要 0.1 添加依赖 org.apache.httpcomponents httpclient 4.5.2 0.2 代码 //1. 打开浏览器 创建httpclient对象 Closeable ...
- TCP模拟HTTP发送get和post请求
环境: 客户端:tcp网络调试助手 服务器:宝塔lamp+thinkphp5.0 客户端TCP连接IP后发送get请求 GET /?key=value&key=value HTTP/1.1 A ...
- C# 模拟浏览器发送post或get请求
一.基本示例 private string HttpPost(string Url, string postDataStr){HttpWebRequest request = (HttpWebRequ ...
- 模拟微信发送文件给好友/群
JAVA模拟微信发送文件给好友/群 通过google开发者模式抓取https://file2.wx.qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json ...
- Java--使用httpClient模拟登陆正方教务系统获取课表
最近形如课程格子与超表课程表应用如雨后春笋般涌现,他们自动获取课程表是怎么实现的呢.于是我用Java实现了一下模拟登陆正方教务系统获取课表的过程. 首先,我们先了解一下网站登录的原理:当我们输入学号, ...
- Java爬虫(二)-- httpClient模拟Http请求+jsoup页面解析
博客 学院 下载 GitChat TinyMind 论坛 APP 问答 商城 VIP会员 活动 招聘 ITeye 写博客 发Chat 传资源 登录注册 原 Java爬虫(二)-- httpClient ...
- JAVA使用HttpClient模拟登录正方教务系统,爬取学籍信息和课程表成绩等,超详细登录分析和代码注解
目录 前言 分析 代码实现 第一次GET POST登录 第二次Get 第三次GET 第四次GET 第五次GET 测试 完整代码 前言 最近在做一个APP,需要获取我们学校--武汉纺织大学皇家停水断电断 ...
最新文章
- c语言合法常量2.57e03,[单选] 目前杭州共有世界遗产()项。
- UpdateData使用简介
- JavaScript 运行机制详解:Event Loop
- 手势检测的回调方法中onfling与onscroll的区别
- winCE改变字库方法(WINCE字库更新)
- node中模板引擎、模块导出、package.json简介
- 视频课程-1小时上手 Spring Boot 及 达梦数据库 做数据展示后端
- Linux学习笔记-管道的读写特性
- Tomcat日志打印乱码解决方法
- 详情和 PoC 发布后,谷歌匆忙修复严重的 Gmail 漏洞
- 十六、Oracle学习笔记:索引和约束(表字段快速查询和约束)
- Linux打开关闭ping
- Atitit 大脑能够储存多大的数据量
- Java从入门到精通(视频教程+源码)
- 【神经网络】RBF神经网络逼近任意连续非线性函数的Simulink仿真
- 数据库系统概论:ER图设计
- 外贸常用术语_2017常用外贸术语大全
- linux netcdf编译,Linux下安装Netcdf
- 8分频verilog线_任意分数分频Verilog实现
- vi 查看最顶部_最详细的 Vi 编辑器使用指南(翻译)