zoukankan      html  css  js  c++  java
  • HttpClient

    使用 HttpClient 需要以下 6 个步骤:

    1. 创建 HttpClient 的实例

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

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

    4. 读 response

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

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

    案例如下:

          HttpClient client = new HttpClient();

         client.setConnectionTimeout(1000 * 60 * 5);

         client.getParams().setContentCharset("utf-8");

         PostMethod method = new PostMethod(“接口地址”);

         Part[] parts = {new FilePart("filedata", pdf),//参数为附件,传入一个文件流

          new StringPart("userNick", URLEncoder.encode("沈飞", "utf-8")) };  

         //method.setParameter("AAA","AAAA");

        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));//设置传送的相关参数

           int status = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {

        System.err.println("Method failed: " + getMethod.getStatusLine());
      }
    

          responseText = method.getResponseBodyAsString();//返回相关信息

         method.releaseConnection(); //释放链接

     

     

    ps: 有get 和post两种方式,案例给的为 post方式,get方式为 

    GetMethod getMethod = new GetMethod("http://www.ibm.com"),getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());

    参数有多中,以上提到两种:

     NameValuePair[] data = { new NameValuePair("id", "youUserName"),    new NameValuePair("passwd", "yourPwd") };

    --针对返回的结果,我们可以用json进行反转

    JSONObject jsonObject = JSONObject.fromObject(responseText);

    jsonObject.get("success")获取相关属性对应的值;

           

  • 相关阅读:
    web site 和 web application的区别
    Windows Phone开发(10):常用控件(上)
    WPF绑定ListBox
    Cookies的实际存储位置
    parse_str() 函数把查询字符串解析到变量中。
    str_repeat() 函数把字符串重复指定的次数。
    搭建Git本地服务器
    windows下github 出现Permission denied (publickey).解决方法
    ReadSolve 规格严格
    Scp命令(转载) 规格严格
  • 原文地址:https://www.cnblogs.com/Snowflake/p/3412218.html
Copyright © 2011-2022 走看看