学习使用OkHttp

学习《Android第一行代码后的笔记》

1、使用前在项目中添加依赖,编辑app/build.gradle文件如下:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    testCompile 'junit:junit:4.12'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
}

添加依赖会自动下载两个库,一个是OkHttp库,一个是Okio库,后者是前者的通信基础。

2、main.xml界面代码如下:

<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:text="发送请求"
       android:layout_width="match_parent"
       android:layout_height="wrap_content" />
    <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="match_parent" />
    </ScrollView>
</LinearLayout>

3、MainActivity代码如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;
    Button sendRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        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){
            sendRequestWithOkHttp();
        }
    }

    private void sendRequestWithOkHttp() {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client=new OkHttpClient();
                    //要发起一个http请求,首先创建一个Request对象
                    Request request=new Request.Builder().url("http://123.206.81.238:8080/xiaomatext/json.json").build();
                    //调用Okhttp的newCall方法返回根据request请求,服务器返回的数据
                    Response response=client.newCall(request).execute();
                    //得到服务器返回的数据的详细内容
                    String responseData=response.body().string();
                    //展示服务器返回的数据到界面上
                    showResponse(responseData.toString());
                }  catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showResponse(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在这里进行UI操作,将结果显示到界面上
                responseText.setText(responseData);
            }
        });
    }
}
3、综合比较OkHttp比HttpURLConnection方便简洁一些。

猜你喜欢

转载自blog.csdn.net/magicmhd/article/details/80691352