zoukankan      html  css  js  c++  java
  • Android网络开发之HttpClient

    Apache提供HttpClient,它对java.net中的类做了封装和抽象,更适合在Android上开发应用。

    HttpClient应用开发几个类:

    1. ClientConnectionManager是客户端连接管理器的接口,

    提供以下几个抽象方法:

    closeIdleConnections, 关闭空闲的连接

    releaseConnection, 释放一个连接

    requestConnection, 请求一个新的连接

    shutdown 关闭ClientConnectionManager并释放资源

    2. DefaultHttpClient是一个默认的Http客户端,可以用来创建一个http连接。

    HttpClient httpClient = new DefaultHttpClient();

    3. HttpResponse是一个http连接响应

    HttpResponse response = httpClient.execute(httpRequest);

    if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)

     

    //  示例代码:HttpGet –> HttpClient –> HttpResponse

    String url = “http://www.txrj.com/reg.jsp?name=jake”;

    HttpGet request = new HttpGet(url);

    HttpClient client = new DefaultHttpClient();

    HttpResponse response = client.execute(request);

    if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

      String data = EntityUtils.toString(response.getEntity());

    }

     

    // 示例代码:HttpPost –> HttpClient –> HttpResponse

    Post方式情况下,需要使用NameValuePair来保存要传递的参数,具体可以使用BasicNameValuePair,然后通过add方法添加到NameValuePair中。

    String url = “http://www.txrj.com/reg.jsp”;

    HttpPost request = new HttpPost(url);

    // 添加参数

    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair(“name”,"jake”));

    // 设置字符集

    HttpEntity entity = new UrlEncodedFormEntity(params, “gb2312”);

    request.setEntity(entity);

    HttpClient client = new DefaultHttpClient();

    HttpResponse response = client.execute(request);

    if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

      String data = EntityUtils.toString(response.getEntity());

    }

  • 相关阅读:
    三元组数据结构
    线性表的顺序表示和实现 数据结构
    【欧拉计划1】Multiples of 3 and 5
    strcmp()与strcmpi()函数 C语言
    指向函数的指针 C语言
    const限定符声明 C语言
    Java环境搭建与配置
    栈的C语言实现
    【欧拉计划2】Even Fibonacci numbers
    单链表的表示和实现 数据结构
  • 原文地址:https://www.cnblogs.com/fengzhblog/p/3185495.html
Copyright © 2011-2022 走看看