Java公共类--HTTP请求

Posted 浮生素语

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java公共类--HTTP请求相关的知识,希望对你有一定的参考价值。

package com.andrew.study.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class HttpUtil {

// 单个参数
public static String sendGet(String url, String param) {
String urlStr = url + "?" + param;
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(urlStr);
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
/*获取所有的请求头
* Map<String, List<String>> heads = connection.getHeaderFields();
for (String key : heads.keySet()) {
System.out.println(key + "--->" + heads.get(key));
}*/
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}

public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader reader = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// post请求必须设置这两项
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
// 获得URLConnection输出流
out = new PrintWriter(connection.getOutputStream());
// 发送请求参数
out.print(param);
// 刷新缓存
out.flush();
// 使用BufferReader输入流来读取url响应
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}

public static void main(String[] args) {
//String string = sendGet("http://www.baidu.com", "");
System.out.println(sendPost("http://localhost:8080/hello1", ""));
}

}






























































































以上是关于Java公共类--HTTP请求的主要内容,如果未能解决你的问题,请参考以下文章

我想使用 Jmeter 使用不同的公共 IP 发送每个 http 请求

Java模拟http请求远程调用接口工具类

java 怎么接收http请求

JAVA http请求工具类http-request

JAVA http请求工具类http-request

java jdk原生的http请求工具类