首页 > 代码库 > Java公共类--HTTP请求
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请求