您的位置:首页 > 运维架构 > Apache

GET方式获取服务器数据---利用apache的jar包

2015-08-14 14:50 615 查看
<span style="font-size:18px;">import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
//使用apache提供的jar包读取服务器返回的数据
public class HttpUtils2
{
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 ClientProtocolException, IOException
{
HttpGet get = new HttpGet(path);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
InputStream in=null;
if(response.getStatusLine().getStatusCode()==200)
{
in = response.getEntity().getContent();
}
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);
}
in.close();
return new String(baos.toByteArray(),code);
}
}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: