zoukankan      html  css  js  c++  java
  • HttpClient下载图片和向服务器提交数据实例

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

    版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29882585/article/details/52244711
    使用 HttpClient 需要以下 6 个步骤:
    1. 创建 HttpClient 的实例
    2. 创建某种连接方法的实例,在这里是GetMethod。在 GetMethod 的构造函数中传入待连接的地址
    3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
    4. 读 response
    5. 释放连接。无论执行方法是否成功,都必须释放连接
    6. 对得到后的内容进行处理
    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("图片下载成功!!!!");
    }
    }
    }

    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);
     }
    }
    }


    ---------------------
    作者:-Sloth-
    来源:CSDN
    原文:https://blog.csdn.net/qq_29882585/article/details/52244711
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    VS2010导入DLL的总结
    [转]C#事件简单示例
    VS2010中实现TreeView和Panel的动态更新
    【JZOJ1282】打工
    【NOIP2016提高A组五校联考2】tree
    【NOIP2016提高A组五校联考2】running
    【NOIP2016提高A组五校联考2】string
    8月~9月学习总结
    NOIP2016提高A组五校联考2总结
    NOIP2016提高A组五校联考1总结
  • 原文地址:https://www.cnblogs.com/handsome1013/p/10728520.html
Copyright © 2011-2022 走看看