HttpURLConnection:从服务器获取数据、网络请求

1.声明权限


2.布局




    

3.activity

public class MainActivity extends AppCompatActivity {

    public static final int SHOW_RESPONSE = 0;
    @BindView(R.id.btn_send_request)
    Button btnSendRequest;
    @BindView(R.id.tv_response)
    TextView tvResponse;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SHOW_RESPONSE:
                    String response = (String) msg.obj;
                    //在这里进行UI操作,将结果显示到界面上
                    tvResponse.setText(response);
                    break;
            }
        }
    };

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

    @OnClick(R.id.btn_send_request)
    public void onViewClicked() {
        sendRequestWithHttpURLConnection();
    }

    /**
     * HttpURLConnection
     */
    private void sendRequestWithHttpURLConnection(){
        //开启线程来发动网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try{
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection)url.openConnection();
                    connection.setRequestMethod("GET");//GET表示从服务器获取数据;POST表示向服务器提交数据
                    connection.setConnectTimeout(8000);//设置连接超时
                    connection.setReadTimeout(8000);//设置读取超时
                    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 message = new Message();
                    message.what = SHOW_RESPONSE;
                    //将服务器返回的结果存放到Message中
                    message.obj = response.toString();
                    handler.sendMessage(message);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(connection != null){
                        connection.disconnect();//将HTTP连接关闭
                    }
                }
            }
        }).start();
        /*//向服务器提交用户名和密码
        connection.setRequestMethod("POST");
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        //每条数据都要以键值对的形式存在,数据与数据之间用&符号隔开
        out.writeBytes("username=admin&password=123");*/
    }

}

你可能感兴趣的:(Android之路)