基本布局:
<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="${relativePackage}.${activityClass}" >
<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>
主程序处理:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequestButton = (Button) findViewById(R.id.send_request);
responseTextView = (TextView) findViewById(R.id.response_text);
sendRequestButton.setOnClickListener(this);
}
按键监听处理:
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
// 200 成功 302 从定向(页面跳转) 404资源没找到 5xx 服务器内部错误
int code = connection.getResponseCode();
while(code==301||code==302)
{
connection=(HttpURLConnection)reload(connection);
code = connection.getResponseCode();
}
if(code==200)
{
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream iStream = connection.getInputStream();
// 读取输入流
BufferedReader bReader = new BufferedReader(
new InputStreamReader(iStream));
StringBuilder response = new StringBuilder();
String line;
byte[] buffer = new byte[1024];
int len = -1;
while ((len = iStream.read(buffer)) != -1) {
line=new String(buffer,0,len);
if(line.contains("charset=gb2312")){//解析meta标签
line=new String(line.getBytes(),"gb2312");
}
response.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message);
}else{
Message message = new Message();
message.what = SHOW_ERROR;
message.obj = code+"";
handler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
处理网页301 302
private static URLConnection reload(URLConnection uc) throws Exception
{
HttpURLConnection huc = (HttpURLConnection) uc;
if (huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM)
// 302, 301
return reload(new URL(huc.getHeaderField("location")).openConnection());
return uc;
}
Handler消息处理:
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseTextView.setText("receive: "+response);
break;
case SHOW_ERROR:
Toast.makeText(getApplicationContext(), "here"+(String) msg.obj, Toast.LENGTH_SHORT).show();
break;
default:
break;
}
};
};
最后不要忘记加上网络权限
<uses-permission android:name="android.permission.INTERNET" />
运行效果: