Java模拟http请求
Java实现http请求主要有3种方式:URLConnection、HttpURLConnection、HttpClient
一
URLConnection 抽象类,属于Java发送http请求的原生api,操作简单
1. 构造URL对象
2. 获取URL对应的URLConnection对象
3. 设置URLConnection的属性值
4. 获取输出流写入数据
5. 获取输入流读取数据
6. 关闭连接
public static void main(String[] args) throws Exception {// 参数可直接拼接到url后URL url = new URL("http://localhost:8080/zwfwxm/honor/getHonor.do"); URLConnection conn = url.openConnection();conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);// json格式的参数时JSONObject param = new JSONObject();param.put("name","Jessic");param.put("gender","female");PrintWriter writer = new PrintWriter(conn.getOutputStream());writer.print(param.toString());writer.flush();if(conn.getResponseCode() != 200){System.out.println("响应码:"+conn.getResponseCode());System.out.println("请求失败:"+conn.getResponseMessage());} else {BufferReader reader = new BufferReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));StringBuffer buffer = new StringBuffer("");String line = "";while((line = reader.readLine() != null){buffer.append(line);}// 返回值是json格式时JSONObject result = JSONObject.fromObject(buffer.toString()); }
}
二
HttpURLConnection 是URLConnection 的抽象子类,请求步骤相差不多
public static void main(String[] args) throws Exception {URL url = new URL("http://localhost:8080/zwfwxm/honor/getHonor.do"); HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setDoOutput(true);// 写入服务器conn.setDoInput(true);// 读取服务器conn.setUseCaches(false);// 使用缓存conn.setInstanceFollowRedirects(true);// 跟随重定向conn.setConnectTimeout(5000);// 控制socket等待建立连接的时间conn.setRequestMethod("POST"); // 设置请求方式conn.setRequestProperty("Accept-Charset", "utf-8");conn.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式conn.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式conn.connect();// json格式的参数时JSONObject param = new JSONObject();param.put("name","Jessic");param.put("gender","female");OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");writer.write(param.toString());writer.flush();if(conn.getResponseCode() != 200){System.out.println("响应码:"+conn.getResponseCode());System.out.println("请求失败:"+conn.getResponseMessage());} else {BufferReader reader = new BufferReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));StringBuffer buffer = new StringBuffer("");String line = "";while((line = reader.readLine() != null){buffer.append(line);}// 返回值是json格式时JSONObject result = JSONObject.fromObject(buffer.toString()); }
}
三
HttpClient
四
RestTemplate
RestTemplate是对HttpClient的再封装,简化了接口请求处理
RestTemplate的初始配置
依赖:
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.6</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.75</version></dependency>
连接配置:
#最大连接数
http.maxTotal=5
#并发数
http.defaultMaxPerRoute=20
#创建连接的最长时间
http.connectTimeout=1000
#从连接池中获取到连接的最长时间
http.connectionRequestTimeout=500
#数据传输的最长时间
http.socketTimeout=10000
#提交请求前测试连接是否可用
http.staleConnectionCheckEnabled=false
#可用空闲连接过期时间,重用空闲连接时会先检查是否空闲时间超过这个时间,如果超过,释放socket重新建立
http.validateAfterInactivity=3000000
package com.muchen.springboot.config;import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.apache.http.conn.socket.ConnectionSocketFactory;import java.nio.charset.StandardCharsets;/*** @author zhangfb* @create 2020-12-13 14:26*/
@Configuration
public class HttpRestConfig {@Value("${http.maxTotal}")private Integer maxTotal;@Value("${http.defaultMaxPerRoute}")private Integer defaultMaxPerRoute;@Value("${http.connectTimeout}")private Integer connectTimeout;@Value("${http.connectionRequestTimeout}")private Integer connectionRequestTimeout;@Value("${http.socketTimeout}")private Integer socketTimeout;@Value("${http.staleConnectionCheckEnabled}")private boolean staleConnectionCheckEnabled;@Value("${http.validateAfterInactivity}")private Integer validateAfterInactivity;@Beanpublic RestTemplate restTemplate() {RestTemplate restTemplate = new RestTemplate(httpRequestFactory());// 把StringHttpMessageConverter编码改成UTF8格式restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));return restTemplate;}@Beanpublic ClientHttpRequestFactory httpRequestFactory() {return new HttpComponentsClientHttpRequestFactory(httpClient());}@Beanpublic CloseableHttpClient httpClient() {Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", SSLConnectionSocketFactory.getSocketFactory()).build();PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);connectionManager.setMaxTotal(maxTotal); // 最大连接数connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); //单个路由最大连接数connectionManager.setValidateAfterInactivity(validateAfterInactivity); // 最大空间时间RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout) //服务器返回数据(response)的时间,超过抛出read timeout.setConnectTimeout(connectTimeout) //连接上服务器(握手成功)的时间,超出抛出connect timeout.setConnectionRequestTimeout(connectionRequestTimeout)//从连接池中获取连接的超时时间,超时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool.build();return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).build();}
}
方法:
// getForObject可互相切换使用getForEntitypublic void getTemplate(){String t = restTemplate.getForObject("http://101.23.111.136:2020/cabinet/cabinet/getNumBox?flag=1&areaCode=340500000000",String.class);// 无参数ResponseEntity<String> r1 = restTemplate.getForEntity("http://101.235.111.136:2020/cabinet/cabinet/getNumBox?flag=1&areaCode=340500000000",String.class);// uri动态参数ResponseEntity<String> r2 = restTemplate.getForEntity("http://101.235.111.136:2020/cabinet/cabinet/getNumBox?flag={num}&areaCode={code}",String.class,"1","340500000000");// 使用map封装参数Map map = new HashMap<String,String>();map.put("flag","1");map.put("areaCode","340500000000");ResponseEntity<String> r3 = restTemplate.getForEntity("http://101.235.111.136:2020/cabinet/cabinet/getNumBox",String.class,map);// outSystem.out.println(t);System.out.println(r1.getStatusCode());System.out.println(r1.getStatusCodeValue());System.out.println(r1.getBody());System.out.println(r2.getStatusCode());System.out.println(r2.getStatusCodeValue());System.out.println(r2.getBody());System.out.println(r3.getStatusCode());System.out.println(r3.getStatusCodeValue());System.out.println(r3.getBody());}// postForObject和postForEntity可切换使用public void postTemplate (){HttpHeaders httpHeaders = new HttpHeaders();httpHeaders.setContentType(MediaType.APPLICATION_JSON);// 可以用JSONObject和Map传参数JSONObject jsonObject = new JSONObject();jsonObject.put("url","http://101.235.111.98:8000/share/jxjyxx");jsonObject.put("sfzhm","1234567890");Map<String,String> map = new HashMap<String, String>();map.put("url","http://10.235.11.98:8000/share/jxjyxx");map.put("sfzhm","1234567890");HttpEntity request = new HttpEntity(map,httpHeaders);JSONObject s = restTemplate.postForObject("http://159.203.254.61:2014/MasTaskCenter/services/wst/getInfoFromXxb", request, JSONObject.class);ResponseEntity<JSONObject> jsonObjectResponseEntity = restTemplate.postForEntity("http://159.203.254.61:2014/MasTaskCenter/services/wst/getInfoFromXxb", request, JSONObject.class);// 使用exchange指定请求方式ResponseEntity<JSONObject> exchange = restTemplate.exchange("http://159.203.254.61:2014/MasTaskCenter/services/wst/getInfoFromXxb", HttpMethod.POST, request, JSONObject.class);System.out.println(s);System.out.println(jsonObjectResponseEntity.getBody());System.out.println(exchange.getBody());}
服务端处理请求
服务端时正常的controller
@RequestMapping("/getHonor")private void getHonor(HttpServletRequest request, HttpServletResponse response) throws IOException{
// 当请求参数拼接到url后时,可使用下面的取参方式,否则需从输入流中取值
// String name = request.getParameter("name");
// String age = request.getParameter("age");
// System.out.println("=====name=="+name + "age=="+age);BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));String line = "";StringBuffer requestStr = new StringBuffer();while((line = br.readLine()) != null){requestStr.append(line);}System.out.println("requestStr=="+requestStr);JSONObject requestObj = JSONObject.fromObject(requestStr.toString());String name = requestObj.getString("name");String age = requestObj.getString("gender");JSONObject result = new JSONObject();result.put("Name", "resp:"+name);result.put("Age", "resp:"+age);response.setCharacterEncoding("utf-8");response.setContentType("application/json; charset=utf-8");PrintWriter out = response.getWriter();out.print(result.toString());}
Java模拟http请求相关推荐
- curl命令java_上curl java 模拟http请求
最近,我的项目要求java模拟http请求,获得dns解决 tcp处理过的信息特定的连接. java api提供urlConnection apache提供的httpClient都不能胜任该需求,二次 ...
- java模拟HTTP请求(集合了网上搜来的各种)
Java发送http请求 (get 与 post方法请求) Java发送http请求 (get 与post方法请求),以下代码经本人亲自调试可用!可以直接使用之. 注意:通过BufferedReade ...
- JAVA模拟HTTP请求中GET/POST方式
package com.nxt.datacenter.utils;/*** 文件描述** @author: maomi* @date: 2019/5/31*/import java.io.Buffer ...
- Java模拟Http请求远程接口
最近业务需要请求远程API接口,并返回相应的数据,同步到公司的服务器.因此编写了下面两个方法,主要是用Java.net.URL模拟http请求,主要写了POST和GET两个方法. 1.GET请求 /* ...
- java模拟浏览器请求HttpUtils,可秒杀京东优惠券
2019独角兽企业重金招聘Python工程师标准>>> package com.boot.utils;import java.io.BufferedReader; import ja ...
- 用Java模拟post请求(也有hutool的HttpUtil使用)
目录 第一种:post多个文件 第二种:参数以json的格式post到服务器 第三种:将key:value的值post到服务端 第一种:post多个文件 客户端的使用方法: 需要注意的点: 这里是为了 ...
- java模拟post请求上传图片
本文档为个人博客文档系统的备份版本.作者:小游.作者博客:点击访问 /*** @description 模拟form表单,上传图片* @param fileName -- 图片路径* @return ...
- java模拟https请求_java-用httpclient模拟发送https请求
--调用项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求. ---但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而jquery的po ...
- java模拟post请求,HttpURLConnection--代码积累
public JSONObject postRequest(Map<String,String> paramMap,String URL) throws Exception { JSONO ...
最新文章
- 从谷歌辞职后,作为独立开发者的第三年,我从年入 3 万做到了年入 40 万
- 《用广义CNOT门产生质数幂维的图态》
- ModuleNotFoundError: No module named 'rospkg'
- python: 关于解决‘\u‘开头的字符串转中文的方法
- linux 进程参数文件 /proc/pid/cmdline 简介
- LeetCode Reconstruct Itinerary(欧拉回路)
- mybatis plus使用雪花算法_MyBatis-Plus进阶
- LeetCode 16最接近的三数之和
- python sorted函数
- 如何求最小三元组距离
- java计算机毕业设计ssm+vue高校科研管理系统
- 5种常见的网络欺骗方式
- arcgis更改字段名_了解字段属性、别名和表显示选项
- what to benefit from the C++14 Standard
- cad怎么改光标样式_如何更改CAD光标大小及颜色?
- sonar打包出现的问题The forked VM terminated without saying properly goodbye. VM crash or System.exit called
- 评'深圳妙龄女白领控诉 要求“熬夜衰老”算工伤'
- windows下maven打包镜像并推送docker服务器
- 大半夜睡不着,聊一下在小外包公司工作一年后的感想吧
- 冒泡排序-过程详细版
热门文章
- html涟漪特效,基于WebGL的炫酷元素背景水波涟漪jQuery特效
- 设计漂亮的样式表是一门艺术(译)
- 苹果手机把游戏藏在计算机,七个一定要知道的Iphone隐藏小技巧,很实用,我知道的太晚了...
- vscode格式化失效问题
- 中国社交网站(SNS)弊端——隐私
- PHP获取当前时间的前一年、一天、一小时、一分钟
- Win7遇到:应用程序已停止工作,故障模块 ntdll.dll
- 主要责任、 主要技术
- 线上服务 CPU 100%?一键定位 so easy!
- 天然气阶梯是按年还是按月_燃气自采暖阶梯气儿价按自然年算