首页 > 代码库 > Java网络编程笔记3

Java网络编程笔记3

如何使用POST请求和GET请求向Web站点发送请求,参考以下代码:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class GetTest {
	private String url;
	private String param;
	/**
	 * 
	 * @param url  发送请求的URL
	 * @param param 请求参数,格式满足name1=value1&name2=value2的形式
	 */
	public GetTest(String url,String param){
		this.url=url;
		this.param=param;
	}
	public String sendGet() throws Exception{
		String result="";
		String urlName=url+"?"+param;
		URL surl=new URL(urlName);
		//打开和URL之间的连接
		URLConnection conn=surl.openConnection();
		//设置通用的请求属性
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		//建立实际的连接
		conn.connect();
		//定义字节流
		InputStream is=conn.getInputStream();
		//包装字符流
		InputStreamReader isr=new InputStreamReader(is,"utf-8");
		//加入缓冲区
		BufferedReader br=new BufferedReader(isr);
		String line;
		while(null!=(line=br.readLine())){
			result+=line;
		}
		br.close();
		isr.close();
		is.close();
		return result;
	}
}

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

public class PostTest {
	private String url;
	private String param;
	/**
	 * 
	 * @param url  发送请求的URL
	 * @param param 请求参数,格式满足name1=value1&name2=value2的形式
	 */
	public PostTest(String url,String param){
		this.url=url;
		this.param=param;
	}
	public String sendGet() throws Exception{
		String result="";
		URL surl=new URL(url);
		//打开和URL之间的连接
		URLConnection conn=surl.openConnection();
		//设置通用的请求属性
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		//发送POST请求必须设置如下两行
		conn.setDoOutput(true);
		conn.setDoInput(true);
		
		PrintWriter pw=new PrintWriter(conn.getOutputStream());
		//发送请求
		pw.print(param);
		pw.flush();
		
		//定义字节流
		InputStream is=conn.getInputStream();
		//包装字符流
		InputStreamReader isr=new InputStreamReader(is,"utf-8");
		//加入缓冲区
		BufferedReader br=new BufferedReader(isr);
		String line;
		while(null!=(line=br.readLine())){
			result+=line;
		}
		br.close();
		isr.close();
		is.close();
		return result;
	}
}

转载请注明出处:http://blog.csdn.net/hai_qing_xu_kong/article/details/40784691     情绪控_ 

Java网络编程笔记3