Send an HTTP request using Android HttpURLConnection

Here, we already learn HttpURLConnection usage of official recommendations.

To get to the first instance of HttpURLConnection

We just need a new URL object, and pass the destination URL, and then call openConnection () method.
URL url=new URL("http://www.baidu.com");
        HttpURLConnection connection=(HttpURLConnection) url.openConnection();

After obtaining the HttpURLConnection example, we can set the HTTP request method is used, there are two common methods: GET and POST. GET want to get data from the server there, POST wish to submit data to the server inside.

connection.setRequestMethod("GET");

The rest, we can make some freedom of customization, such as setting a link timeout, timeout milliseconds to read, and hope to get some of the server message header. Such as:

connection.setConnectTimeout(8000);
        connection.setReadTimeout(8000);

After recalling the getInputStream () method can be used to obtain the input stream returned from the server, that remains is to read the input stream, then call disconnec () method in this connection is closed off HTTP, as shown:

InputStream in=connection.getInputStream();
        connection.disconnect();

After all the parts are finished presentation, we will use an example to experience the usage under the HttpURLConnection.
XML layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/BT"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

Activities section:

Button sendRequest=(Button)findViewById(R.id.BT);
        responseText=(TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                    HttpURLConnection connection=null;
                        BufferedReader reader=null;
                     try{
                     URL url=new URL("http://www.sina.com");
                            connection=(HttpURLConnection) url.openConnection();
                            connection.setRequestMethod("GET");
                            connection.setReadTimeout(8000);
                            connection.setReadTimeout(8000);

                            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(responseData);
                        }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() {
                        responseText.setText(response);
                    }
                });

            }
        });

So we put HttpURLConnection send the contents of the HTTP request to finish, but after reading the OkHttp usage, we may not again HttpURLConnection up. Next blog I wrote OkHttp in the end is how to use.
Now he is still a white, Guo Lin put the teacher's own understanding of the knock again, if students want to come with Android learn, we can learn together.

Published 37 original articles · won praise 10 · views 10000 +

Guess you like

Origin blog.csdn.net/OneLinee/article/details/78369129