HttpClient简单使用方法详解

来源:互联网 发布:分辨率 像素 知乎 编辑:程序博客网 时间:2024/06/17 03:24

HttpClient使用详解

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。


使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

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

三 实例

1.布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="HttpClient请求" />

    <TextView
        android:id="@+id/TextView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        />

  </RelativeLayout>

2.MainActivity
package com.example.zhou;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceActivity.Header;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends Activity {

    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //得到控件
        tv = (TextView ) findViewById(R.id.TextView1);
        Button getCli = (Button) findViewById(R.id.button1);
        //按钮监听事件
        getCli.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
MyTask myTask = new MyTask();
String path = "http://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10";
myTask.execute(path);

}
});
        
    }
   
    //mytask类
    private class MyTask extends AsyncTask<String, Integer, String>{


private String string;
@Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(params[0]);
    try {   
    //得到请求码
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.d("zzz", httpResponse.toString());
//判读是否请求成功
if (httpResponse.getStatusLine().getStatusCode()==200) {
HttpEntity entity = httpResponse.getEntity();
String string = EntityUtils.toString(entity, "utf-8");

return string;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//结束时的方法
    @Override
    protected void onPostExecute(String result) {
   
tv.setText(result.toString());
}
    } 
}
3.配置
项目清单文件中
<uses-permission android:name="android.permission.INTERNET"/>
build. gradle中
android{    useLibrary'org.apache.http.legacy'}


原创粉丝点击