使用HttpURLConnection访问百度首页
package com.jackie.networktest;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private Button btnSend;
private TextView tvResponse;
//用于收发消息进行UI更新
private Handler handler = new Handler() {
/**
* 在主线程更新TextView中的内容
* @param msg
*/
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {
String response = ((StringBuilder) msg.obj).toString();
tvResponse.setText(response);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = (Button) findViewById(R.id.btnSend);
tvResponse = (TextView) findViewById(R.id.tvResponse);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//访问网络是耗时操作,开辟子线程
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL("http://www.baidu.com");
//向百度服务器发起Http请求
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(8000);
httpURLConnection.setReadTimeout(8000);
//获得服务器返回的字节流
InputStream is = httpURLConnection.getInputStream();
//包装成输入流
InputStreamReader isr = new InputStreamReader(is);
//包装成缓冲流
BufferedReader br = new BufferedReader(isr);
//使用StringBuilder来保存字符
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
Message message = new Message();
message.what = 1;
message.obj = sb;
//通知handler,封装返回的数据
handler.sendMessage(message);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭连接
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
}
}).start();
}
});
}
}
这里返回的是最原始的HTML代码片。
使用HttpClient访问百度首页
这个方法现在实际上已经过时了,因为这个类是Apache提供的,
sdk6.0以后取消了HttpClient,设置android SDK的编译版本为23时,且使用了httpClient相关类的库项目,会出现有一些类找不到的错误。
解决方法有两种:
1.在相应的module下的build.gradle
useLibrary 'org.apache.http.legacy'
这句一定要加在 android{ } 当中。
如:
android {
useLibrary 'org.apache.http.legacy'
}
2.将在相应的module下的build.gradle中修改compileSdkVersion的值,设置为更小的sdk版本
将上面的代码改为
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String entity = EntityUtils.toString(httpEntity, "utf-8");
Message message = new Message();
message.what = 1;
message.obj = entity;
handler.sendMessage(message);
返回的是同样的页面