HttpClient客户端

来源:互联网 发布:藏刀不能在淘宝卖 编辑:程序博客网 时间:2024/05/01 17:48
HttpCient  客户端
请求:HttpGet   HttpPost
响应:HTTPResponse
URI:统一资源标识符 uniform   resource  identify
 1、HttpGet请求使用步骤:
       a、创建客户端,实例化HttpClient     
       b、创建get请求,指定请求资源的地址
       c、客户端执行get请求,服务器返回HttpResponse对象
       d、根据返回的状态码,判断是否成功(200),之后使用流进行读写操作
案例:
                String path = "http://localhost:8080/HttpConn26/27125332.jpg";
HttpClient client = new DefaultHttpClient();//创建客户端,实例化HttpClient     
HttpGet get = new HttpGet(path);创建get请求,指定请求资源的地址
HttpResponse res = client.execute(get);客户端执行get请求,服务器返回HttpResponse对象
if (res.getStatusLine().getStatusCode() == 200) {//根据返回的状态码,判断是否成功(200),之后使用流进行读写操作
HttpEntity entity = res.getEntity();//通过响应,获得实体
InputStream is = entity.getContent();//通过实体,获得输入流
FileOutputStream fos = new FileOutputStream("c:/w.jpg");
int len = 0;      
                                byte[] b = new byte[1024];
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
fos.flush();
                                 }
------------------------------------------------------------------------------------
代码优化:使用实体的工具类,这样就不用再使用流来读取
   byte[] buf = EntityUtils.toByteArray(entity);
   String line = EntityUtils.toString(entity);
------------------------------------------------------------------------------------
2、HttpPost请求
      a、创建客户端
      b、创建post请求,封装资源地址
      c、向服务器上传数据
      d、客户端执行post请求,返回响应
      e、根据响应的状态码,如果是200,进行读写操作
案例:
String path = "http://localhost:8080/webDay26/TestServlet";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(path);
try {
                         //发送数据以实体的形式发送数据
NameValuePair p1 = new BasicNameValuePair("username", "admin");//创建名值对
NameValuePair p2 = new BasicNameValuePair("password", "123");
List<NameValuePair> list = new ArrayList<NameValuePair>();//创建集合,存储名值对
list.add(p1);
list.add(p2);
HttpEntity entity = new UrlEncodedFormEntity(list);//创建实体,封装存储名值对的集合
post.setEntity(entity);//给post请求设置实体,实体封装了发送的数据


HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == 200) {
System.out.println(EntityUtils.toString(res.getEntity()));
}
0 0
原创粉丝点击