AndroidはHTTPプロトコルを使用してネットワークにアクセスします

HTTPプロトコルを使用してネットワークにアクセスする

HttpURLConnectionを使用する

これまで、AndroidでHTTPリクエストを送信するには、HttpURLConnectionとHttpClientの2つの方法がありました。
ただし、APIが多すぎる、拡張が難しいなどのHttpClientの欠点があるため、Androidチームはこの方法の使用をますます思いとどまらせています。最後に、Android 6.0システムでは、HttpClientの機能が完全に削除され、この機能が正式に廃止されました。

まず、HttpURLConnectionのインスタンスを取得する必要があります。通常は、次のように、新しいURLオブジェクトを作成し、ターゲットネットワークアドレスを渡してから、openConnection()メソッドを呼び出すだけです。

	URL url = new URL("http://www.baidu.com");
	HttpURLConnection connection = (HttpURLConnection) url.openConnection();

HttpURLConnectionのインスタンスを取得した後、HTTPリクエストで使用されるメソッドを設定できます。主に2つの一般的に使用されるメソッド、GETとPOSTがあります。GETはサーバーからデータを取得することを意味し、POSTはサーバーにデータを送信することを意味します。書き込み方法は次のとおりです
。connection.setRequestMethod( "GET");
次に、リンクタイムアウト、読み取りタイムアウトのミリ秒数、サーバーが取得を希望するメッセージヘッダーの設定など、無料のカスタマイズを行うことができますこの部分は実際の状況に応じて書かれており、例は次のとおりです。

	connection.setConnectionTimeout(8000);
	connection.setReadTimeout(8000);

次に、getInputStream()メソッドを呼び出して、サーバーから返された入力ストリームを取得します。残りのタスクは、以下に示すように、入力ストリームを読み取ることです。

	InputStream in = connection.getInputStream();

最後に、以下に示すように、disconnect()メソッドを呼び出してHTTPリンクを閉じることができます。

	connection.disconnect();

例を通してHttpURLConnectionの使用法を体験してみましょう。新しいNetworkTestプロジェクトを作成し、最初
にactivity_main.xmlのコードを変更します

<?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/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"
        />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

crollView。これを使用すると、画面外のコンテンツの一部をスクロール形式で表示できます。さらに、ButtonとTextViewがレイアウトに配置されます。ButtonはHTTP要求を送信するために使用され、TextViewはサーバーから返されたデータを表示するために使用されます。

次に、コードMainActivityのコードを次のように変更します。

package net.nyist.lenovo.networktest;


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
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;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

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){
                //sendRequestWithHttpURLConnection();
                sendRequestWithOkHttp();
            }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("https://www.baidu.com")
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void sendRequestWithHttpURLConnection() {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://www.baidu.com");
                    connection =(HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(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(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);
            }
        });
    }
}

HTTPプロトコルを使用してネットワークにアクセスする

おすすめ

転載: blog.csdn.net/i_nclude/article/details/77758224