jdk-httpclient
jdk自带发送http请求的类,不需要第三方依赖
发送get请求和post请求
发送get请求
BufferedReader in = null;
StringBuffer strBuf = new StringBuffer();
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 定义BufferedReader输入流来读取URL的响应
InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
in = new BufferedReader(inputStreamReader);
String line;
while ((line = in.readLine()) != null) {
strBuf.append(line);
strBuf.append("\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
设置请求参数
conn.setRequestProperty("content-type", "application/json");
封装一个简单的get方法
public StringBuffer get(String url, Map<String, String> headers) {
URLConnection conn = null;
try {
URL realUrl = new URL(url);
conn = realUrl.openConnection();
} catch (IOException e1) {
e1.printStackTrace();
}
if (headers != null) {
for (Map.Entry<String, String> e : headers.entrySet()) {
conn.setRequestProperty(e.getKey(), e.getValue());
}
}
// 定义BufferedReader输入流来读取URL的响应
BufferedReader in = null;
StringBuffer strBuf = new StringBuffer();
try {
InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
in = new BufferedReader(inputStreamReader);
String line;
while ((line = in.readLine()) != null) {
strBuf.append(line);
strBuf.append("\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return strBuf;
}
使用get方法
Map<String, String> hdeader = new HashMap<>();
hdeader.put("content-type", "application/json");
StringBuffer strBuf = get(url, hdeader);
发送post请求
发送 post json
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连