Thanlon

高雅的志趣,人生才不会迷茫。牵一恋人而终生,得一志趣而无悔。------2018年6月13日。
posts - 143, comments - 15, trackbacks - 0, articles - 0
  首页 :: 管理

公告

安卓中使用HttpURLConnection连接网络简单示例 --Android网络编程

Posted on 2018-06-12 13:36 牛新龙的个人博客 阅读(...) 评论(...) 编辑 收藏

MainActivity.java:

package thonlon.example.cn.httpurlconnectionpro;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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 btn_req;
  private TextView tv_res;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
  }

  private void initView() {
    btn_req = (Button) findViewById(R.id.btn_req);
    tv_res = (TextView) findViewById(R.id.tv_res);
  }

  public void onClick(View view) {
    sendRequestHttpURLConnection();
  }

  public void sendRequestHttpURLConnection() {
    new Thread(new Runnable() {
      @Override
      public void run() {
        String urlStr = "https://www.baidu.com";
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        try {
        URL url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(8000);
        conn.setReadTimeout(8000);
        InputStream is = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
        response.append(line);
        }
        showResponse(response.toString());
        } catch (MalformedURLException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          if (reader != null) {
          try {
            reader.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        if (conn != null) {
          conn.disconnect();
        }
      }
     }
  }).start();
}

  private void showResponse(final String response) {
    runOnUiThread(new Runnable() {
    @Override
    public void run() {
      tv_res.setText(response);
    }
  });
}
}