您的位置:首页 > 理论基础 > 计算机网络

android使用httpClient访问网络

2015-11-11 08:45 615 查看
首先发一下效果:



读者觉得好像乱码?先不要急,待我稍微解说一下。

在代码中,我们请求的目标地址就是百度首页,我们按下send Request的button后,我们直接向服务器发送请求并且获取数据,而服务器返回给我们的正是如此的html代码,只是通常情况,浏览器都会将这些代码解析成漂亮的网页后再显示出来。我们可以用chrome打开百度首页,按下F12看一下html代码:



MainActivity:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

public static final int SHOW_RESPONSE = 0;

private Button sendRequest;

private TextView responseText;

private Handler handler = new Handler() {

public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
}

};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.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是一个接口,我们通常情况先要创建一个DefaultHttpClient实例
// 指定访问的服务器地址是百度首页
//首先要创建一个HttpGet对象
//然后调用execute()方法
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
//执行execute()之后会返回一个HttpResponse对象
//服务器返回的所有信息都会包在这里面
//通常情况我们都会先取出服务器返回的状态码,等于200说明请求和响应都成功了
if (httpResponse.getStatusLine().getStatusCode() == 200) {
//调用getEntity()获取到一个HttpEntity实例
//然后在用EntityUtils.toString()将HttpEntity转化成字符串
//相信大家对utf-8万国码还是不陌生的
//最后将服务器返回的结果存放到Message中
//使用handler把内容在textview中显示出来
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}

}

activity_main:
<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_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>

</LinearLayout>

不要忘记在此处加上手机访问网络的权限。

AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.networktest"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.networktest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息