android使用HttpURLConnection获取网站源码

基本布局:
   
   
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical"
  6. tools:context="${relativePackage}.${activityClass}" >
  7. <Button
  8. android:id="@+id/send_request"
  9. android:layout_width="match_parent"
  10. android:layout_height="wrap_content"
  11. android:text="Send Request" />
  12. <ScrollView
  13. android:layout_width="match_parent"
  14. android:layout_height="match_parent" >
  15. <TextView
  16. android:id="@+id/response_text"
  17. android:layout_width="match_parent"
  18. android:layout_height="wrap_content" />
  19. </ScrollView>
  20. </LinearLayout>
主程序处理:
   
   
  1. @Override
  2. protected void onCreate(Bundle savedInstanceState) {
  3. super.onCreate(savedInstanceState);
  4. setContentView(R.layout.activity_main);
  5. sendRequestButton = (Button) findViewById(R.id.send_request);
  6. responseTextView = (TextView) findViewById(R.id.response_text);
  7. sendRequestButton.setOnClickListener(this);
  8. }
按键监听处理:
   
   
  1. @Override
  2. public void onClick(View arg0) {
  3. // TODO Auto-generated method stub
  4. if (arg0.getId() == R.id.send_request) {
  5. sendRequestWithHttpURLConnection();
  6. }
  7. }
  8. private void sendRequestWithHttpURLConnection() {
  9. new Thread(new Runnable() {
  10. @Override
  11. public void run() {
  12. // TODO Auto-generated method stub
  13. HttpURLConnection connection = null;
  14. try {
  15. URL url = new URL("http://www.baidu.com");
  16. connection = (HttpURLConnection) url.openConnection();
  17. // 200 成功 302 从定向(页面跳转) 404资源没找到 5xx 服务器内部错误
  18. int code = connection.getResponseCode();
  19. while(code==301||code==302)
  20. {
  21. connection=(HttpURLConnection)reload(connection);
  22. code = connection.getResponseCode();
  23. }
  24. if(code==200)
  25. {
  26. connection.setRequestMethod("GET");
  27. connection.setConnectTimeout(8000);
  28. connection.setReadTimeout(8000);
  29. InputStream iStream = connection.getInputStream();
  30. // 读取输入流
  31. BufferedReader bReader = new BufferedReader(
  32. new InputStreamReader(iStream));
  33. StringBuilder response = new StringBuilder();
  34. String line;
  35. byte[] buffer = new byte[1024];
  36. int len = -1;
  37. while ((len = iStream.read(buffer)) != -1) {
  38. line=new String(buffer,0,len);
  39. if(line.contains("charset=gb2312")){//解析meta标签
  40. line=new String(line.getBytes(),"gb2312");
  41. }
  42. response.append(line);
  43. }
  44. Message message = new Message();
  45. message.what = SHOW_RESPONSE;
  46. message.obj = response.toString();
  47. handler.sendMessage(message);
  48. }else{
  49. Message message = new Message();
  50. message.what = SHOW_ERROR;
  51. message.obj = code+"";
  52. handler.sendMessage(message);
  53. }
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. } finally {
  57. if (connection != null) {
  58. connection.disconnect();
  59. }
  60. }
  61. }
  62. }).start();
  63. }
处理网页301 302
   
   
  1. private static URLConnection reload(URLConnection uc) throws Exception
  2. {
  3. HttpURLConnection huc = (HttpURLConnection) uc;
  4. if (huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP || huc.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM)
  5. // 302, 301
  6. return reload(new URL(huc.getHeaderField("location")).openConnection());
  7. return uc;
  8. }
Handler消息处理:
   
   
  1. private Handler handler = new Handler() {
  2. public void handleMessage(android.os.Message msg) {
  3. switch (msg.what) {
  4. case SHOW_RESPONSE:
  5. String response = (String) msg.obj;
  6. // 在这里进行UI操作,将结果显示到界面上
  7. responseTextView.setText("receive: "+response);
  8. break;
  9. case SHOW_ERROR:
  10. Toast.makeText(getApplicationContext(), "here"+(String) msg.obj, Toast.LENGTH_SHORT).show();
  11. break;
  12. default:
  13. break;
  14. }
  15. };
  16. };

最后不要忘记加上网络权限
   
   
  1. <uses-permission android:name="android.permission.INTERNET" />

运行效果:
device-2016-10-15-184618.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值