一、HttpClient用法
- HttpClient是接口,因此无法创建它的实例,通常情况下都会创
建一个 DefaultHttpClient 的实例 - 创建一个 HttpGet 对象,传入目标的网络地址
- 调用 HttpClient 的 execute()方法
- 返回一个 HttpResponse 对象
- 取出服务器返回的状态码,如果等于 200 就说明请求和响应成功
- 调用 getEntity()方法获取到一个 HttpEntity 实例
EntityUtils.toString()将 HttpEntity 转换成字符串
二、具体实例
1.建立布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/response"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
2.添加权限
3.MainActivity
public class MainActivity extends ActionBarActivity implements OnClickListener {
public static final int SHOW_RESPONSE = 0;
private Button button;
private TextView responseText;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
responseText.setText(response);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithHttpClient();
}
}
private void sendRequestWithHttpClient() {
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");
Message msg = Message.obtain();
msg.what = SHOW_RESPONSE;
msg.obj = response;
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}