如果只是简单的页面请求和接口调用,不设计其它复杂操作,比如缓存、登录等,HttpURLConnection基本可以满足业务需求
文中部分信息是从网上找过来的,其中的上传和下载代码块,没有做过验证,这里只是记录一下作为一个模板参考。
一、GET请求
public static void submitGet() {
try {
URL url = new URL("www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);//设置该连接是可以输出的
//设置connection是否自动执行http重定向,网页响应状态为3xx那些
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("GET");//设置请求方式
//有的网站设置了必须是浏览器请求才会回应,所以需要User-Agent参数可以随意设置浏览器值和版本
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36");
//头结构
//请求方的HTTP报头结构:通用报头|请求报头|实体报头
//响应方的HTTP报头结构:通用包头|响应报头|实体报头
//Accept报头代表发送端(客户端)希望接受的数据类型。比如:Accept:text/xml;代表客户端希望接受的数据类型是xml类型
connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
//Content-Type报头代表发送端(客户端|服务器)发送的实体数据的数据类型。比如:Content-Type:text/html;代表发送端发送的数据格式是html
//二者结合起来,Accept:text/xml;Content-Type:text/html;即代表希望接受的数据类型是xml格式,本次请求发送的数据的数据格式是html
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//用来说明访问者希望采用的语言或语言组合
connection.setRequestProperty("Accept-Language", "zh-cn");
//代表客户端CPU的类型或制造商
connection.setRequestProperty("UA-CPU", "x86");
/**
*为什么设置gzip而不是deflate,原因是有些网站他不管你能接受什么压缩格式,统统也会压缩网页内容传给你。当然IE,FF能处理好这些内容,
*所以我们通过浏览器查看的时候是正常的。一般gzip的压缩可以将一个33K的文件压缩成7K,这样会节约不少带宽,但服务器的负荷并没有减轻,
*因为他要压缩文件呀。至于为什么不用deflate,是由于绝大多数网站的压缩方式是用gzip,而在有些网站中,明明是用的gzip却返回deflate的压缩标识。
*这有什么意义呢,所以干脆就告诉服务器,我不接受deflate,因为他太丑了,又长,哪像gzip这么潮呀。
*对于浏览量大的静态网页服务器,这样做很是必要。100M的独享服务器,他也只有100M呀。
*/
connection.setRequestProperty("Accept-Encoding", "gzip");
//keep-Alive有什么用呢,你不是在访问网站,你是在采集。嘿嘿。减轻别人的压力,也是减轻自己。
//允许客户端和服务器指定与请求/响应连接有关的选项
connection.setRequestProperty("Connection", "close");
//缓存,true使用缓存,false不使用缓存
connection.setUseCaches(false);
//打开连接超时,单位毫秒
connection.setConnectTimeout(6*1000);
//读取超时,单位毫秒
connection.setReadTimeout(6*1000);
//获取服务器端对正文的压缩方式,大部分是gzip,很少deflate(ZLIB),也有可能返回空
String encode = connection.getContentEncoding().toLowerCase();
//GZIPInputStream此类为读取 GZIP 文件格式的压缩数据实现流过滤器。
if(encode.indexOf("gzip") >= 0) {
InputStream in = new GZIPInputStream(connection.getInputStream());
}
//获取http响应状态码,200,400等这些
int code = connection.getResponseCode();
//获取和http响应状态码一起返回的http响应消息,如果有的话
String codeMessage = connection.getResponseMessage();
//读取网站返回内容流
BufferedReader buff = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
//读取返回的前10K内容,包含完整头信息就行
//这个判断没有任何含义,请直接无视
if(3%2 > 0) {
char[] chars = new char[10 * 1024];
buff.read(chars, 0, 10 * 1024);
}
String line=null;
StringBuilder result = new StringBuilder();
while((line = buff.readLine()) != null) {
result.append(line+"\r\n");
}
connection.disconnect();
// System.out.println(result.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
二、POST请求,一些头信息设置请参考上面的GET请求
public static void submitPost() {
try {
URL url = new URL("www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//设置可输入
connection.setDoOutput(true);//设置该连接是可以输出的
connection.setRequestMethod("post");//设置请求方式
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
pw.write("参数");
pw.flush();
pw.close();
BufferedReader buff = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gbk"));
String line = null;
StringBuilder result = new StringBuilder();
while((line = buff.readLine()) != null) {
result.append(line+"\r\n");
}
connection.disconnect();
System.out.println(result.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
三、POST请求,参数为JSON,一些头信息设置请参考上面的GET请求
public void submitPostJSON() {
try {
URL url = new URL("www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);//设置可输入
connection.setDoOutput(true);//设置该连接是可以输出的
connection.setRequestMethod("POST");//设置请求方式
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
Map<String, String> data = new HashMap<String, String>();
data.put("api_id", "sendMsg");
data.put("phone","18516584059");
data.put("content", "hello,world!!");
PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
pw.write(JSON.toJSONString(data));
pw.flush();
pw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
StringBuilder result = new StringBuilder();
while((line = br.readLine()) != null) {
result.append(line+"\r\n");
}
connection.disconnect();
System.out.println(result.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
四、HTTP下载文件
public static void downloadFile() {
try {
URL url = new URL("www.baidu.com");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//设置连接超时
urlConn.setConnectTimeout(5 * 1000);
//设置读取超时
urlConn.setReadTimeout(5 * 1000);
//是否使用缓存
urlConn.setUseCaches(true);
//请求方式
urlConn.setRequestMethod("GET");
//设置头信息,设置请求中的媒体类型信息
urlConn.setRequestProperty("Content-Type", "application/json");
//设置客户端与服务连接类型
urlConn.addRequestProperty("Connection", "Keep-Alive");
//开始连接
urlConn.connect();
//判断连接成功
if (urlConn.getResponseCode() == 200) {
//存储位置
String pathFile = "";
File descFile = new File(pathFile);
FileOutputStream fos = new FileOutputStream(descFile);
//每次读取大小
byte[] buffer = new byte[1024];
int len;
//读取服务器返回内容
InputStream inputStream = urlConn.getInputStream();
while ((len = inputStream.read(buffer)) != -1) {
//写入本地
fos.write(buffer, 0, len);
}
}else {
System.out.println("连接失败,下载失败");
}
urlConn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
五、HTTP上传文件
public static void upLoadFile(HashMap<String, String> paramsMap) {
try {
URL url = new URL("www.baidu.com");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//设置该连接允许读取
urlConn.setDoOutput(true);
//设置该连接允许写入
urlConn.setDoInput(true);
//设置不能使用缓存
urlConn.setUseCaches(false);
//设置连接超时时间
urlConn.setConnectTimeout(5 * 1000);
//设置读取超时时间
urlConn.setReadTimeout(5 * 1000);
//设置请求方式
urlConn.setRequestMethod("POST");
//设置维持长连接
urlConn.setRequestProperty("connection", "Keep-Alive");
//设置文件字符集
urlConn.setRequestProperty("Accept-Charset", "UTF-8");
//设置文件类型
urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + "*****");
//
File file = new File("");
String name = file.getName();
DataOutputStream requestStream = new DataOutputStream(urlConn.getOutputStream());
requestStream.writeBytes("--" + "*****" + "\r\n");
//发送文件参数信息
StringBuilder tempParams = new StringBuilder();
tempParams.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + name + "\"; ");
int pos = 0;
int size=paramsMap.size();
for (String key : paramsMap.keySet()) {
tempParams.append( String.format("%s=\"%s\"", key, paramsMap.get(key), "utf-8"));
if (pos < size-1) {
tempParams.append("; ");
}
pos++;
}
tempParams.append("\r\n");
tempParams.append("Content-Type: application/octet-stream\r\n");
tempParams.append("\r\n");
String params = tempParams.toString();
requestStream.writeBytes(params);
//发送文件数据
FileInputStream fileInput = new FileInputStream(file);
int bytesRead;
byte[] buffer = new byte[1024];
DataInputStream in = new DataInputStream(new FileInputStream(file));
while ((bytesRead = in.read(buffer)) != -1) {
requestStream.write(buffer, 0, bytesRead);
}
requestStream.writeBytes("\r\n");
requestStream.flush();
requestStream.writeBytes("--" + "*****" + "--" + "\r\n");
requestStream.flush();
fileInput.close();
int statusCode = urlConn.getResponseCode();
if(statusCode == 200) {
//获取返回的数据
String result = streamToString(urlConn.getInputStream());
}else {
System.out.println("上传失败");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String streamToString(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
byte[] byteArray = baos.toByteArray();
return new String(byteArray);
} catch (Exception e) {
return null;
}
}