HttpURLConnection基本使用

2019-08-20  本文已影响0人  者文_

1. HttpURLConnection基本使用

HttpURLConnection是网络请求的基本类,在具体了解HttpURLConnection的基本使用前,先了解一些RUL

1.1 URL介绍

统一资源定位符URL(Uniform Resource Locator)是www客户机访问Internet时用来标识资源的名字和地址。

URL的基本格式是:

<METHOD>://<HOSTNAME:PORT>/<PATH>/<FILE>  

示例:

http://www.weixueyuan.net/view/6079.html (www.weixueyuan.net是主机名,view/6079.html是文件路径和文件名)

简单的可以把URL理解为包含:协议、主机名、端口、路径、查询字符串和参数等内容。每一段可以独立设置。

Java中有个java.net包,其中的类是进行网络编程的,URL对象则是一个可以表示网络资源的类。程序利用URL对象能够实现Internet寻址、网络资源的定位连接、在客户机与服务器之间访问等。

URL对象的方法也很简单,基本上都是get方法,主要用于分段获取一个URL中各个部分,比单纯地使用一个字符串来表示链接地址,URL对象的方式更加灵活方便。

同时,它可以使用openConnection方法,获取一个URLConnection对象,以建立网络连接。

1.2 HttpURLConnection使用

HttpURLConnection的基本使用步骤如下:

示例

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            Log.e("MainActivity","first");
            sendRequestWithHttpURLConnection();
        }
    }

    private void sendRequestWithHttpURLConnection() {
        //开启线程发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    //获取HttpRULConnection实例
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    //设置请求方法和自由定制
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    //获取响应码和返回的输入流
                    int i = connection.getResponseCode();
                    InputStream in = connection.getInputStream();
                    //对输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse( final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //进行UI操作
                responseText.setText(response);
            }
        });
    }
}

在AndroidManifest.xml中注册权限

<uses-permission android:name="android.permission.INTERNET"/>

备注:(Android 9.0不能明文连接,需用https

示例2:从网络中下载图片

备注

上一篇 下一篇

猜你喜欢

热点阅读