分享一个向Web站点发送GET请求、POST请求的工具类,方便以后使用。
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 GetPostUtil {
public static String sendGet(String url, String parmas) {// parmas是请求参数,格式为name1=valuel&name2=value2
String result = "";
BufferedReader in = null;
String urlName = url + "?" + parmas;
try {
URL realUrl = new URL(urlName);
// 打开和URL间的链接
URLConnection con = realUrl.openConnection();
// 设置通用的请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible;MSIE 6.0; Windows NT 5.1; SV1)");
// 建立实际链接
con.connect();
// 获取所以响应头字段
Map
> map = con.getHeaderFields();
for (String key : map.keySet()) {
System.out.println(key + "----->" + map.get(key));
}
// 读取URL的响应
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
// ///
public static String sendPost(String url, String parmas) {// parmas是请求参数,格式为name1=valuel&name2=value2
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL间的链接
URLConnection con = realUrl.openConnection();
// 设置通用的请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible;MSIE 6.0; Windows NT 5.1; SV1)");
// 发送POST请求必须设置如下两行
con.setDoOutput(true);
con.setDoInput(true);
// 获取URLConnection对象的输出流
out = new PrintWriter(con.getOutputStream());
// 发送请求参数
out.print(parmas);
out.flush();
// 定义BufferReader输入流来读取URL响应
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += "\n" + line;
}
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}