Java网络编程实现HTTP请求方式
Java网络编程实现HTTP请求方式
在现今繁忙的互联网时代,向服务器发送HTTP请求是很常见的一种操作。HTTP请求中GET和POST两种方式是最常见的使用方式,而Java语言模拟实现就是有一定技巧的。下面将介绍如何使用Java网络编程实现HTTP GET POST请求方式。
代码示例
// 发送GET请求
public static String sendGet(String url, String param) throws IOException {
String result = "";
String urlNameString = url + "?" + param;
URL realURL = new URL(urlNameString);
// 打开和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)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map"">> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if (in != null) {
in.close();
}
return result;
}
// 发送POST请求
public static String sendPost(String url, String param) throws IOException {
String result = "";
URL realURL = new URL(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);
// 获取URLConnection对象对应的输出流
PrintWriter out = new PrintWriter(connection.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
return result;
}
</string,>
用户评论