通常创建一个URL的连接并发送请求、读取此URL引用的资源的步骤如下:
1、调用URL的openConnection()方法来创建URLConnection对象
2、设置URLConnection的参数和普通请求属性
3、如果只是发送GET方式请求,使用connect方法建立和远程资源之间的实际连接就行;如果需要发送POST方式的请求,需要获取URLConnection实例对应的输出流来发送请求参数
4、远程资源变得可用,程序可以访问远程资源的头字段或通过输入流来读取远程资源的数据
程序实例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class GetPostTest {
/**
* 向指定url发送get请求
* @param url 发送请求的url
* @param param 请求参数
*/
public static String sendGet(String url,String param){
String result = "";
BufferedReader in = null;
try{
String urlName = url + "?" + param;
URL readUrl = new URL(urlName);
//打开url连接
URLConnection conn = readUrl.openConnection();
//设置请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
conn.connect();
Map<String, List<String>> map = conn.getHeaderFields();
//遍历所有响应头字段
for(String key : map.keySet()){
System.out.println(key + "-------->" + map.get(key));
}
//定义输入流来读取url的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream())
);
String line;
while((line = in.readLine()) != null){
result += "\n" + line;
}
}catch(Exception e){
System.out.println("发送get请求出现异常" + e);
e.printStackTrace();
}finally{
try{
if(in != null){
in.close(); //关闭输入流
}
}catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定url发送post请求
* @param url 发送请求的url
* @param param 请求参数
*/
public static String sendPost(String url,String param){
PrintWriter out = null;
String result = "";
BufferedReader in = null;
try{
URL readUrl = new URL(url);
//打开url连接
URLConnection conn = readUrl.openConnection();
//设置请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
//发送请求参数
out.print(param);
//输出流的缓冲
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream())
);
String line;
while((line = in.readLine()) != null){
result += "\n" + line;
}
}catch (Exception e){
System.out.println("发送post请求出现异常" + e);
e.printStackTrace();
}finally {
try{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
}catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static void main(String[] args) {
//发送get请求
String s = GetPostTest.sendGet("http://www.csdn.net/?ref=toolbar", null);
System.out.println(s);
//发送post请求
String s1 = GetPostTest.sendPost("http://blog.csdn.net/william_hangshao/article/details/65636141", null);
System.out.println(s1);
}
}