OKHttp网络请求——get、post请求

来源:互联网 发布:js控制svg 编辑:程序博客网 时间:2024/05/21 04:40

Okhttp主要包含:

● get请求、post请求

● 基于Http的文件上传

● 文件下载

● 加载图片

● 支持请求回调;支持返回对象、对象集合

● 支持session的保持

使用前,对于Android Studio的用户,可以选择添加依赖:

compile 'com.squareup.okhttp:okhttp:2.4.0'

注意:okhttp内部依赖okio,同时导入

compile 'com.squareup.okio:okio:1.5.0'

------Get请求的步骤------

1:首先构造一个Request对象,可以通过Request.Buider设置参数;

2:然后通过Request构造得到一个Call对象,类似于将你的请求封装成了任务,既是任务,就会有execute()cancel()等方法。

3:最后,我们希望以异步的方式进行请求,所以我们调用的是call.enqueue();将call加入请求调度队列,然后等待任务执行完成,我们在CallBack中即可得到结果。

在使用时需要注意:

OnResponse回调的参数是response,

如果我们希望获得返回的字符串,可以通过response.body().string();获取

如果我们希望获得返回的是二进制字节数组,可以通过response.body().bytes();获取

如果我们希望获得返回的是InputStream,则调用response.body().byteStream();获取

onResponse执行的线程并不是UI线程,操作控件时还需要使用Handler等。

package xixinxin.bawie.com.android_okhttp_study;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.widget.TextView;import com.squareup.okhttp.Call;import com.squareup.okhttp.Callback;import com.squareup.okhttp.FormEncodingBuilder;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.Request;import com.squareup.okhttp.Response;import java.io.IOException;public class MainActivity extends AppCompatActivity {    private TextView tv;    Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            if (msg.what == 0) {                String data = (String) msg.obj;                tv.setText(data);                Log.i("xxx", data);            }            if (msg.what == 1) {                String data = (String) msg.obj;                tv.setText(data);                Log.i("xxx", data);            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        tv = (TextView) findViewById(R.id.tv);//        getData();        postData();    }    private void postData() {        //创建OKHttpClient对象        OkHttpClient mOKHttpClient = new OkHttpClient();        String url = "http://api.ehuigou.com/Orders/searchCartsLog";        //创建FormEncodingBuilder 用来封装参数        FormEncodingBuilder mFeb = new FormEncodingBuilder();        mFeb.add("store_id", "3850");        //创建request        Request build = new Request.Builder().url(url).post(mFeb.build()).build();        //得到Call        Call call = mOKHttpClient.newCall(build);        call.enqueue(new Callback() {            @Override            public void onFailure(Request request, IOException e) {            }            @Override            public void onResponse(Response response) throws IOException {                String string = response.body().string();                Message message = handler.obtainMessage(1, string);                message.sendToTarget();            }        });    }    private void getData() {        //创建OKHttpClient对象        OkHttpClient mOKHttpclient = new OkHttpClient();        String url = "http://www.93.gov.cn/93app/data.do?" + "channelId=" + 0 + "&startNum=" + 0;        //创建request对象        Request request = new Request.Builder().url(url).build();        //得到Call        Call call = mOKHttpclient.newCall(request);        call.enqueue(new Callback() {            @Override            public void onFailure(Request request, IOException e) {            }            @Override            public void onResponse(Response response) throws IOException {                String string = response.body().string();                Message message = handler.obtainMessage(0, string);                message.sendToTarget();            }        });    }}
//依赖
compile 'com.squareup.okhttp:okhttp:2.4.0'compile 'com.squareup.okio:okio:1.5.0'

0 0