学习使用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方便简洁一些。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值