The one day 使用网络技术-->HttpURLConnection
这一节是关于Http协议访问网络,
http协议的工作原理非常简单,就是客户端向服务器发出一条http请求,然后服务器收到请求之后返回给客户端一些数据,然后客户端在将这些数据进行解析和处理;
HTTP常用的方法有主要有两个 :GET和POST;GET表示希望从服务器获取数据,POST表示希望向服务器提交数据;
创建NetWorkTest
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="demo.mrlong.com.networktest.MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Http Get" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
Java代码:
public class MainActivity extends Activity {
//定义一个整型常量
public static final int SHOW_RESOPNSE = 1;
private Button btn;
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn);
text = (TextView)findViewById(R.id.text);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequestWithHttpConnection();
}
});
}
/×
因为android不允许在子线程中进行UI操作,但有些时候,我们必须在子线程中去执行这些操作。异步消失处理机制,完美的解决了这个问题。
这时候这个方法是在主线程中进行的,所以我们可以放心的对UI进行操作;
×/
private android.os.Handler handler = new android.os.Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESOPNSE:
String response = (String) msg.obj;
//进行UI操作
text.setText(response);
}
}
};
private void sendRequestWithHttpConnection(){
new Thread(new Runnable() {
@Override
public void run() {
//首先我们需要一个HttpURLConnection 实例;
HttpURLConnection connection = null;
try {
//new出一个URL对象,传入目标网络地址;
URL url = new URL("http://www.baidu.com");
//调用openConnection()方法即可;
connection =(HttpURLConnection)url.openConnection();
//设置HTTP请求所使用的方法;
connection.setRequestMethod("GET");
//设置连接超时,读取超时的毫秒数;
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
//调用getInputStream()方法获取服务器返回的输入流
InputStream in = connection.getInputStream();
//对输入流进行读取;
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine() )!= null){
response.append(line);
}
/×
异步消息处理机制,
创建一个Message对象,并将what字段指定为SHOW_RESOPNSE, 将服务器返回的数据放入message', 调用handler的sendmessage方法将这条message发送出去,很快Handler就会收到这条Message;
×/
Message message = new Message();
message.what = SHOW_RESOPNSE;
message.obj = response.toString();
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
finally {
if(connection != null){
//关闭http连接
connection.disconnect();
}
}
}
}).start();
}
}
最后,不要忘记声明权限:<uses-permission android:name="android.permission.INTERNET"/>
HttpClient
HttpClient是Apache提供的http网路访问的接口,从一开始就被引入到了android的API中,它可以完成和HttpURLConnextion几乎一模一样的效果,但两者的用法却有很大的差别,
首先我们需要知道,HttpClient是一个接口,因此无法创建它的实例,通常情况下会new一个DefaultClient的实例,
HttpClient httpClient = new DefaultHttpClient();
接下来如果想要发出一条网络请求,我们就需要new一个HttpGet对象,并传入目标网络地址,
HttpGet httpGet = new HttpGet("http://www.baidu.com");
接下来调用HttpClient的execute()方法,并将get对象传入;
HttpResponse httpResponse =httpClient.execute(httpGet);
取出服务器返回的状态码。判断请求是否成功;(200表示成功)
调用getEntity()方法取到httpEntity实例;
然后在用EntityUtils.toString()这个静态方法转换成字符串;
if(httpResponse.getStatusLine().getStatusCode() == 200){
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity, "utf-8");
下面是NetWorkTest中sendRequestWithHttpConnection()方法用httpClient实现:
private void sendRequestWithClient(){
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 message = new Message();
message.what = SHOW_RESOPNSE;
message.obj = response.toString();
handler.sendMessage(message);
}
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}

浙公网安备 33010602011771号