原 OkHttp 3.0之后版本GET、POST请求以及POST上传文件的示例代码

转载请标明出处: 
http://blog.csdn.net/ming2316780/article/details/51598063 
本文出自:【Android_Jerry的博客】

首先说一下2.x到3.x关于POST请求的请求体类的改变:

在2.x中是 类名是:FormEncodingBuilder() 
在3.x中是 类名是: FormBody,但是一般使用是 FormBody.builder()

目前网上很多示例代码都是基于2.x缩写的,我看了很多也没发现3.x的示例代码。无意间搜索okhttp3包内类时,发现了FormBody这个类,才知道原来是类名换掉了。于是我又上okhttp官网查找更新说明,但是并没找到相关说明。

就此,我就把我写的简单示例代码分享一下吧:

源码下载请点此处

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private OkHttpClient client;
    public static final String GET_URL = "http://bz.budejie.com/?typeid=2&ver=3.4.3&no_cry=1&client=android&c=wallPaper&a=wallPaperNew&index=1&size=60&bigid=0";
    public static final String TYPE = "application/octet-stream";
    public static final String POST_URL = "http://zhushou.72g.com/app/gift/gift_list/";
    //    请求条件:platform=2&gifttype=2&compare=60841c5b7c69a1bbb3f06536ed685a48
    public static final String POST_URL2 = "http://admin.wap.china.com/user/NavigateTypeAction.do?processID=getNavigateNews";
    //    请求参数:page=1&code=news&pageSize=20&parentid=0&type=1

    private TextView tvShow;

    private void assignViews() {
        tvShow = (TextView) findViewById(R.id.tv_show);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        assignViews();
        initOkHttp();
    }

    private void initOkHttp() {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
    }
    //此处为按钮点击事件:Get请求、Post请求、Post上传文件
    public void okhttp(View view) {
        switch (view.getId()) {
            case R.id.btn_get:   //Get请求
                Request request = new Request.Builder()
                        .get()
                        .url(GET_URL)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String string = response.body().string();
//                        Log.i(TAG, "onResponse: "+string);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvShow.setText(string);
                            }
                        });
                    }
                });
                break;
            case R.id.btn_post:   //Post请求
                //    请求条件:platform=2&gifttype=2&compare=60841c5b7c69a1bbb3f06536ed685a48
                //    请求参数:page=1&code=news&pageSize=20&parentid=0&type=1
                RequestBody requestBodyPost = new FormBody.Builder()
                        .add("page", "1")
                        .add("code", "news")
                        .add("pageSize", "20")
                        .add("parentid", "0")
                        .add("type", "1")
                        .build();
                Request requestPost = new Request.Builder()
                        .url(POST_URL)
                        .post(requestBodyPost)
                        .build();
                client.newCall(requestPost).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String string = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tvShow.setText(string);
                            }
                        });
                    }
                });
                break;
            case R.id.btn_post_file:   //Post请求上传文件
                File file = new File(Environment.getExternalStorageDirectory(), "dd.mp4");
                if (!file.exists()) {
                    Toast.makeText(MainActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
                } else {
                    RequestBody fileBody = RequestBody.create(MediaType.parse(TYPE), file);
                    RequestBody requestBody = new MultipartBody.Builder().addFormDataPart("filename", file.getName(), fileBody).build();

                    Request requestPostFile = new Request.Builder()
                            .url("http://10.11.64.50/upload/UploadServlet")
                            .post(requestBody)
                            .build();
                    client.newCall(requestPostFile).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, final Response response) throws IOException {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tvShow.setText(response.toString());
                                }
                            });
                        }
                    });
                }
                break;
        }
    }
}

github地址:https://github.com/AndroidJerry8/OkHttpDemo

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

原 OkHttp 3.0之后版本GET、POST请求以及POST上传文件的示例代码

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭