05
2017
10

okHttp基本使用

okHttp的异步get请求:

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url("http://10.0.2.2:8080/myweb/test.json")
            .method("GET",null)
            .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 {
           String str = response.body().string();
           Log.d("TAG",str);
        }
    });

注意onResponse的回调并不是在UI线程。

oKHttp的同步get请求:

      new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://10.0.2.2:8080/myweb/test.json")
                            .method("GET",null)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.d("TAG",responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

这里是同步请求网络需要在子线程中执行。

服务端搭建可参考:HttpURLConnection的post请求上传键值对和json数据
oKHttp的POST上传键值对:

        RequestBody requestBody = new FormBody.Builder()
                .add("username","admin")
                .add("password","123456")
                .build();
        Request request = new Request.Builder()
                .url("http://10.0.2.2:8080/test4/test")
                .post(requestBody)
                .build();
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    Log.d("TAG",response.body().string());
                }
            }
        });

oKHttp上传JSON类型数据:

        Map<String,String> map = new HashMap<String,String>();
        map.put("id","5");
        map.put("version","3.0");
        map.put("name","beach");
        Gson gson = new Gson();
        String str = gson.toJson(map);
        //定义上传文件类型为JSON类型
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(JSON,str);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://10.0.2.2:8080/test4/test")
                .post(requestBody)
                .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 {
                if(response.isSuccessful()){
                    Log.d("TAG",response.body().string());
                }
            }
        });

oKHttp的post上传文件到服务器

        //getFilesDir()方法用于获取/data/data/<application package>/files目录
        File file = new File(getFilesDir(),"okhttp.txt");
        try {
            FileOutputStream out = new FileOutputStream(file);
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write("Hello oKHttp");
            writer.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown;charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(MEDIA_TYPE_MARKDOWN,file);
        Request request = new Request.Builder()
                .url("http://10.0.2.2:8080/test4/test")
                .post(requestBody)
                .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 {
                if(response.isSuccessful()){
                    Log.d("TAG",response.body().string());
                }
            }
        });

源码下载

上一篇:AndroidGPS和基站定位 下一篇:Swift:"奇怪"的事件响应链