HttpClient的使用

HttpClient是Apache提供的HTTP网络访问接口,从一开始 的时候就被引入到了AndroidAPI中,它可以完成和HttpURLConnection几乎一模一样的效果,但两者之间的用法却有较大的差别。

1、首先我们要知道HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例,如下所示:

HttpClient httpClient=new DefaultHttapClient();

2、如果想要发起一条GET请求,就可以创建一个HttpGet对象,并传入目标网络地址,然后调用HttpClient的execute()方法即可:

HttpGet httpGet=new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);

3、如果发起一条POST请求会GET稍微复杂一点,我们需要创建一个HttpPost对象,并传入目标的网络地址,如下所示:

HttpPost httpPOst=new HttpPost("http://www.baidu.com");

4、然后通过NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法构建好的UrlEncodedFormEntity传入,如下所示:

List<NameValuePair> params=new ArrayList<NameValuePair>();
List<NameValuePair> params=new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username","admin"));
                params.add(new BasicNameValuePair("password","123456"));
                UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf_8");
                httpPost.setEntity(entity);

5、接下来的操作就和HttpGet一样了,调用HttpClient的execute()方法,并将HttpPost对象传入即可:

httpClient.execute(httpPost);

6、执行execute()方法之后会返回一个HttpResponse对象,服务器所返回的所用信息就会包含在里面。通常情况下我们会先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了,如下所示:

if(httpResponse.getStatusLine.getStatusCode()==200){
//请求和响应都成功了
}

7、接下来在这个if判断的内部取出服务返回的具体内容,可以调用getEntity()方法获取到一个HttpEntity实例,然后在调用EntityUtils.toString()这个静态 方法将HttpEntity转换成字符串即可,如下所示:

HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity);

注意:如果服务器返回的数据是带有中文的,直接调用EntityUtils.toString()方法进行转换会有乱码的情况出现,这个时候只需要在转换的时候将字符集指定成utf-8就可以了,如下所示:

String response=EntityUtils.toString(entity,"utf-8");

9、要取出服务器返回的内容,在调用getEntity()方法取得HttpEntity实例后,也可以用得到输入流的方法,从输入流中在返回的数据。如下所示:

InputStream is=entity.getContent();//得到输入流
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String line=br.readLine();
                    while (line!=null){
                    System.out.println(line);
                       line=br.readLine();
                    }
                }

HttpClientActivity

public class HttpClientActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mButtonDoGet;
    private Button mButtonDoPost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_httpclient);
        mButtonDoGet= (Button) findViewById(R.id.button_doget);
        mButtonDoGet.setOnClickListener(this);
        mButtonDoPost= (Button) findViewById(R.id.button_dopost);
        mButtonDoPost.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
switch (v.getId()){
    case R.id.button_doget:
        MyAsyncTask task=new MyAsyncTask();
        task.execute();
        break;
    case R.id.button_dopost:
        break;
}

    }
    class MyAsyncTask extends AsyncTask<String ,Integer,String>{
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            HttpClient client=new DefaultHttpClient();
            //"http://192.168.0.198:8080/MyAndroidServlet/MyServlet?name=kangsang&password=123"
            String urlString="http://192.168.0.43:8080/www/MyserverTest?name=liujiaorui&password=123456";
            HttpGet get=new HttpGet(urlString);//设置为get方法
            //设置服务器接收后的数据以utf-8的方式读取
            get.setHeader("Content_Type","application/x-www-form-urlencoded;charset=UTF-8");

            try {
                HttpResponse response=client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中
                StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码
                int code=statusLine.getStatusCode();//得到状态码
                if (code== HttpURLConnection.HTTP_OK){
                    HttpEntity entity=response.getEntity();//得到数据的实体
                    InputStream is=entity.getContent();//得到输入流
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String line=br.readLine();
                    while (line!=null){
                    System.out.println(line);
                       line=br.readLine();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "连接成功";
        }
    }
}

布局

<Button
    android:id="@+id/button_doget"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="GET"/>
    <Button
        android:id="@+id/button_dopost"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="POST"/>
HttpClient 是一个开源的 HTTP 客户端库,用于发送 HTTP 请求和接收 HTTP 响应。它提供了简化的 API,使得进行 HTTP 通信变得更加容易。 要使用 HttpClient,首先需要在项目中引入 HttpClient 的依赖。具体的操作方式取决于你使用的开发环境和构建工具。一般来说,如果是使用 Maven 进行项目管理,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` 如果是使用 Gradle 进行项目管理,可以在 build.gradle 文件中添加以下依赖: ```groovy implementation 'org.apache.httpcomponents:httpclient:4.5.13' ``` 接下来就可以在代码中使用 HttpClient 来发送 HTTP 请求了。下面是一个简单的示例: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet("http://example.com"); HttpResponse response = httpClient.execute(request); System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); } } ``` 上述示例中,我们创建了一个 HttpClient 实例,并使用该实例发送了一个 GET 请求到 "http://example.com"。获取到的响应存储在 HttpResponse 对象中,我们可以通过调用 `getStatusCode()` 方法获取响应的状态码。 当然,HttpClient 还提供了丰富的 API,可以进行更加复杂的 HTTP 请求和处理。你可以参考 HttpClient 的官方文档来了解更多详细的使用方法和示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值