Java 发送http GET/POST请求
最近项目里面需要用到Java发送http请求,由于发送https请求有点复杂,暂时不考虑
HttpURLConnection
HttpURLConnection是一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。
HttpURLConnection是Java的标准类,它继承自URLConnection,可用于向指定网站发送GET请求、POST请求。它在URLConnection的基础上提供了如下便捷的方法:
int getResponseCode(); // 获取服务器的响应代码。
String getResponseMessage(); // 获取服务器的响应消息。
String getResponseMethod(); // 获取发送请求的方法。
void setRequestMethod(String method); // 设置发送请求的方法。
如何使用
HTTP请求方法有8种,分别是GET、POST、DELETE、PUT、HEAD、TRACE、CONNECT 、OPTIONS。其中PUT、DELETE、POST、GET分别对应着增删改查。
GET:请求获取Request-URI所标识的资源
POST:在Request-URI所标识的资源后附加新的数据
HEAD:请求获取由Request-URI所标识的资源的响应消息报头
PUT: 请求服务器存储一个资源,并用Request-URI作为其标识
DELETE :请求服务器删除Request-URI所标识的资源
TRACE : 请求服务器回送收到的请求信息,主要用于测试或诊断
CONNECT: HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。
OPTIONS :请求查询服务器的性能,或者查询与资源相关的选项和需求
返回的数据格式化json 用的是 com.google.gson.*;
开始
(1)包
import com.google.gson.*;
import java.io.*;
import java.net.*;
(2)发送GET请求
public static JsonObject getXpath(String requestUrl) {
String res = "";
JsonObject object = null;
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
System.out.println(urlCon.getResponseCode());
if (200 == urlCon.getResponseCode()) {
InputStream is = urlCon.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String str = null;
while ((str = br.readLine()) != null) {
buffer.append(str);
}
br.close();
isr.close();
is.close();
res = buffer.toString();
JsonParser parse = new JsonParser();
object = (JsonObject) parse.parse(res);
} else {
throw new Exception("连接失败");
}
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
(3)发送POST请求
public static JsonObject postDownloadJson(String path, String post) {
URL url = null;
try {
url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 提交模式
httpURLConnection.setRequestMethod("POST");
//连接超时 单位毫秒
httpURLConnection.setConnectTimeout(10000);
//读取超时 单位毫秒
httpURLConnection.setReadTimeout(2000);
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
//post的参数 xx=xx&yy=yy
printWriter.write(post);
// flush输出流的缓冲
printWriter.flush();
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
byte[] arr = new byte[1024];
while ((len = bis.read(arr)) != -1) {
bos.write(arr, 0, len);
bos.flush();
}
bos.close();
JsonParser parse = new JsonParser();
return (JsonObject) parse.parse(bos.toString("utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
如果需要用到登录情况,可以先发送登录请求保存cookie,第二次发送就可以请求了
(4)保存cookie
通过这两行代码就可以把网站返回的cookie信息存储起来,下次访问网站的时候,自动帮你把cookie信息带上。
//存储cookie
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
通过返回的json获取值(子节点)
JsonElement cookie = res.get("data").getAsJsonObject().get("cookie");
超时无响应问题设置
//连接超时 单位毫秒
httpURLConnection.setConnectTimeout(10000);
//读取超时 单位毫秒
httpURLConnection.setReadTimeout(2000);
Java 发送http GET/POST请求的更多相关文章
- Java发送get及post请求工具方法
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...
- JAVA发送http get/post请求,调用http接口、方法
import java.io.BufferedReader; import java.io.IOException;import java.io.InputStream; import java.io ...
- Java发送http get/post请求,调用接口/方法
由于项目中要用,所以找了一些资料,整理下来. GitHub地址: https://github.com/iamyong 转自:http://blog.csdn.net/capmiachael/a ...
- JAVA发送http GET/POST请求的两种方式+JAVA http 请求手动配置代理
java发送http get请求,有两种方式. 第一种用URLConnection: public static String get(String url) throws IOException { ...
- Java 发送Get和Post请求
package com.htpt.superviseServices.dm.util; import java.io.BufferedReader; import java.io.IOExceptio ...
- java发送GET和post请求
package com.baqingshe.bjs.util; import java.io.BufferedReader; import java.io.IOException; import ja ...
- 如何用java发送Http的post请求,并传递参数
书写方法,请参考以下代码: package utils; import java.io.BufferedReader; import java.io.IOException; import java. ...
- java发送post 的json请求
package com.elink.estos.mq.mqmanager; import java.io.IOException; import java.io.InputStream; import ...
- 【工具】java发送GET、POST请求
前项目使用这种HTTP的方式进行数据交互,目前已更换数据交互方式,但是作为接口提供调用来说还是比较简洁高效的: 总体流程就是: 1.发送HTTP请求 2.获取返回的JSON对象 3.JSON转换 pa ...
随机推荐
- Java springMVC前端传入字符串、后台接收Date的错误解决
今天在一个基于SSM的项目里出现以下报错 Cannot convert value of type [java.lang.String] to required type [java.util.Dat ...
- MySQL之级联删除、级联更新、级联置空
1. 准备测试表 # 专业表major ))engine=innodb default charset=utf8; # 学生表mstudent ), major int)engine=innodb d ...
- Docker|部署及简单使用
环境:VMware + centos7 + docker17.05.0 一.安装docker 1.修改ifcfg-ens33 配置虚拟机的网络,保证可以正常联网 命令:vi /etc/sysconfi ...
- javascript中对一个对象数组按照对象某个属性进行排序
需求:对timelist排序 安装keys . 分析:timelist 是个数组对象,里面包含属性 keys,val.这里借助数组sort方法 传入function <script> // ...
- 常用app分类
西瓜视频 今日头条(极速版) 喜马拉雅 扫描全能王 蜻蜓FM 每天影视 抖音 小读 樊登读书 微信读书 懒人听书 京东 找靓机 拼多多 淘宝 小米有品 当当 什么值得买 小米商城 淘票票 懂车帝 小红 ...
- Laravel中的Storage::disk
Laravel中的Storage::disk 一.总结 一句话总结: Storage的disk的路径和file的路径都是一回事,都是config/filesystems.php配置文件中disks 比 ...
- Phpstudy 无法启动mysql
原因: 两个mysql版本冲突 本地已经有一个mysql服务(3306)默认开启,再装了phpstudy又会自带一个mysqlla服务(3306) phpstudy启动后会启动mysqlla 发现3 ...
- hive匹配中文
select regexp_extract('ab中文123测试55..', '[\u4e00-\u9fa5]+', 0) 只提出成功第一段中文汉字,结果为: 中文 select regexp_rep ...
- EnvironmentError: mysql_config not found
Collecting MySQL-python==1.2.5 (from -r requirementsNoGit.txt (line 9)) Using cached https://files.p ...
- SpringMVC RequestLoggingFilter log to file
spring - How to Log HttpRequest and HttpResponse in a file? - Stack Overflowhttps://stackoverflow.co ...