GET方式从服务器获取数据

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.client.ClientProtocolException;
//从服务器获取数据
public class HttpUtils1
{
	public static void main(String[] args) throws ClientProtocolException, IOException
	{
		String path = "http://localhost:8080/day01";
		InputStream in = HttpUtils2.getInputStream(path);
		System.out.println(HttpUtils2.getResult(in, "utf-8"));		
	}
	//得到能获取服务器数据的读取流
	public static InputStream getInputStream(String path) throws IOException
	{
		URL url = new URL(path);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		
		con.setRequestMethod("GET");
		con.setConnectTimeout(5000);
		con.setDoInput(true);
		
		InputStream in =null;
		if(con.getResponseCode()==200)
		{
			in = con.getInputStream();
		}
		return in;
	}
	//通过读取流把服务器数据读到本地内存
	public static String getResult(InputStream in,String code) throws IOException
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len=0;
		while((len=in.read(b))!=-1)
		{
			baos.write(b,0,len);
		}
		return new String(baos.toByteArray(),code);
	}
	
}

你可能感兴趣的:(GET方式从服务器获取数据)