Android 工具类httpClient

来源:互联网 发布:九次方大数据 上市 编辑:程序博客网 时间:2024/05/17 23:21

jar包下载

httppost

private static void Httppost() {//创建HttpClientBuilder  HttpClientBuilder newBuilder = HttpClientBuilder.create();  CloseableHttpClient newClient = newBuilder.build();  //接口地址String url="";//httppostHttpPost newHttppost=new HttpPost(url);//默认配置postnewHttppost.setConfig(RequestConfig.DEFAULT);//post数据String postString="";//post实体StringEntity entity=new StringEntity(postString,"UTF-8");try {   newHttppost.setEntity(entity);   //执行httppost请求   HttpResponse httpResponse=newClient.execute(newHttppost); //获取响应实体    HttpEntity httpEntity=httpResponse.getEntity();    //响应状态    System.out.println("StatusLine: " +httpResponse.getStatusLine());     if (httpEntity != null) {              System.out.println("contentEncoding:" +             httpEntity.getContentEncoding());             System.out.println("response content:" +             EntityUtils.toString(httpEntity));        }      } catch (IOException e) {          e.printStackTrace();      } finally {          try {          //关闭流并释放资源              newClient.close();      } catch (IOException e) {          e.printStackTrace();      }  }  }

httpget

private static void HttpGet() {//创建Client    HttpClientBuilder newBuilder=HttpClientBuilder.create();    CloseableHttpClient newClient=newBuilder.build();    //Httpget    HttpGet newHttpget=new HttpGet("http://hq.sinajs.cn/list=sh601006");    System.out.println("RequestLint: " + newHttpget.getRequestLine());    try {        //执行get请求        HttpResponse httpResponse=newClient.execute(newHttpget);        //获取响应实体        HttpEntity httpEntity=httpResponse.getEntity();        //响应状态        System.out.println("StatusLine: " +httpResponse.getStatusLine());         if (httpEntity != null) {                  System.out.println("contentEncoding:" +                 httpEntity.getContentEncoding());                //将返回实体字符串输出                System.out.println("response content:" +                 EntityUtils.toString(httpEntity));            }          } catch (IOException e) {              e.printStackTrace();          } finally {              try {              //关闭流并释放资源                  newClient.close();          } catch (IOException e) {              e.printStackTrace();          }      }  }/**RequestLint: GET http://hq.sinajs.cn/list=sh601006 HTTP/1.1StatusLine: HTTP/1.1 200 OKcontentEncoding:nullresponse content:var hq_str_sh601006="..."*/

传输实体

  1. UrlEncodedFormEntity()
List<NameValuePair> pairs = new ArrayList<NameValuePair>();  NameValuePair pair1 = new BasicNameValuePair("supervisor", supervisorEt.getEditableText().toString());      pairs.add(pair1);        httpPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
  1. StringEntity()
    httpPost.setEntity(new StringEntity(postData.toString(), HTTP.UTF_8));
0 0