您的位置:首页 > 理论基础 > 计算机网络

HttpClient下载图片和向服务器提交数据实例

2016-08-18 20:53 288 查看
使用 HttpClient 需要以下 6 个步骤:

1. 创建 HttpClient 的实例

2. 创建某种连接方法的实例,在这里是GetMethod。在 GetMethod 的构造函数中传入待连接的地址

3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例

4. 读 response

5. 释放连接。无论执行方法是否成功,都必须释放连接

6. 对得到后的内容进行处理

[java] view
plain copy

 print?





public class DemoHttpClient03 {  

    public static void main(String[] args) throws ClientProtocolException, IOException {  

          

        //1,导包  

        //2,得到HttpClient对象  

            HttpClient client = new DefaultHttpClient();  

              

        //3,设置请求方式  

            HttpGet get = new HttpGet("http://photocdn.sohu.com/20150610/mp18368185_1433925691994_5.jpg");  

          

        //4,执行请求, 获取响应信息  

            HttpResponse response = client.execute(get);  

              

            if(response.getStatusLine().getStatusCode() == 200)  

            {  

                //得到实体  

                HttpEntity entity = response.getEntity();  

                  

                byte[] data = EntityUtils.toByteArray(entity);  

                  

                //图片存入磁盘  

                FileOutputStream fos = new FileOutputStream("d:/mpl.jpg");  

                fos.write(data);  

                fos.close();  

                  

                System.out.println("图片下载成功!!!!");     

            }  

    }  

}  

[java] view
plain copy

 print?





public class DemoHttpClient04 {  

    public static void main(String[] args) throws ClientProtocolException, IOException {  

        //1, 导包  

        //2, 得到HttpClient对象  

            HttpClient client = new DefaultHttpClient();  

        //3, 设置请求方式 post  

            HttpPost post = new HttpPost("http://localhost:8080/Day_28_Servlet/LoginServlet");  

        //6, List<BasicNameValuePair>  

            List<BasicNameValuePair> parameters = new ArrayList();  

            BasicNameValuePair p1 = new BasicNameValuePair("useName", "abc");  

            parameters.add(p1);  

              

            BasicNameValuePair p2 = new BasicNameValuePair("usePwd", "123");  

            parameters.add(p2);  

              

        //5, 请求"实体" (封装请求参数的对象)  

            HttpEntity entity = new UrlEncodedFormEntity(parameters);  

        //4, 需要给post中加入参数  

            post.setEntity(entity);  

  

        //7, 执行请求, 获取响应  

            HttpResponse response = client.execute(post);  

          

            if(response.getStatusLine().getStatusCode() ==200)  

            {  

                //得到响应的实体  

                HttpEntity responseEntity  = response.getEntity();  

                  

                String str = EntityUtils.toString(responseEntity);  

                  

                System.out.println("响应的内容为 : " + str);  

            }  

    }  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: