OkHttp3向服务器同步提交各种数据的写法

最近公司业务需要学习OkHttp3,那么就先从写一个关于其基本用法的demo开始。

1、添加依赖包

compile 'com.squareup.okhttp3:okhttp:3.3.0'

2、关于RequestBody

OkHttp3提交的数据时放在RequestBody中的,在提交时需要制定提交的Content-Type。常用的数据类型有

application/x-www-form-urlencoded 数据是个普通表单
multipart/form-data 数据里有文件
application/json 数据是个json
image/jpeg 数据是个图片

关于用对应Content-Type来实现RequestBody用法为

MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, "你的json");

当然这里只是以数据类型为json来举例子。

3、提交json数据类型的代码

客户端提交json数据类型代码为

new Thread(new Runnable() {
            @Override
            public void run() {
                String url = "http://192.168.8.130:8081/test/postJson";
                OkHttpClient httpClient = new OkHttpClient();
                MediaType JSON = MediaType.parse("application/json;charset=utf-8");
                RequestBody body = RequestBody.create(JSON, "{'name':'yjing','age':'12'}");
                Request request = new Request.Builder().url(url).post(body).build();
                Call call = httpClient.newCall(request);
                try {
                    Response response = call.execute();
                    System.out.println("status_code:" + response.code() + response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

服务器端接受json数据类型代码为

@RequestMapping(path = "/postJson",method = RequestMethod.POST)
    @ResponseBody
    public void postJsonData(){
        /*防止乱码*/
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        try{
            InputStream is = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while((line = reader.readLine()) != null){
                sb.append(line);
            }
            System.out.println(sb.toString());
            response.getWriter().append("postJson请求成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

4、提交图片类型数据代码

客户端提交图片类型数据代码为

new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream is = getClass().getResourceAsStream("/assets/default.png");
                    File file = new File(mContext.getExternalCacheDir(),"default.png");
                    OutputStream os = new FileOutputStream(file);
                    int bytesRead = 0;
                    byte[]  buffer = new byte[2048];
                    while((bytesRead = is.read(buffer,0,2048))!= -1){
                        os.write(buffer,0,bytesRead);
                    }
                    os.close();
                    is.close();
                    String url = "http://192.168.8.130:8081/test/postImg";
                    OkHttpClient httpClient = new OkHttpClient();
                    MediaType Text_Plain = MediaType.parse("image/jpeg;charset=utf-8");
                    RequestBody body = RequestBody.create(Text_Plain, file);
                    Request request = new Request.Builder().url(url).post(body).build();
                    Call call = httpClient.newCall(request);
                    Response response = call.execute();
                    System.out.println("status_code:" + response.code() + response.body().string());
                    file.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

这里的图片取的事assets目录下图片,并将其另存为了外部存储空间图片来发送,所以显得有些麻烦。如果有大神指导如何直接取到assets目录图片发送,望指教。

服务器端获取图片数据代码

@RequestMapping(path = "/postImg",method = RequestMethod.POST)
    @ResponseBody
    public void postImgData(){
        try{
            InputStream is = request.getInputStream();
            File file = new File("student.jpg");
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[]  buffer = new byte[2048];
            while((bytesRead = is.read(buffer,0,2048))!= -1){
                os.write(buffer,0,bytesRead);
            }
            os.close();
            is.close();
            response.getWriter().append("postText请求图片成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

由以上可见发送json、文件以及图片服务器端代码都是解析二进制数据流的方式来获取对应数据。
关于一次请求中既有表单数据又有文件的时候,请用Content-Type为multipart/form-data来发送请求,具体的代码就不贴了,网上搜一大把。
同事以上只是用同步请求方式发送数据,对于异步请求也是用类似方法实现,不一而叙。

5、补充

关于具体是用客户端的代码已上传github,这里给个链接吧

https://github.com/Yoryky/AndroidDemo.git

6、引用文献

1、http://www.jianshu.com/p/1873287eed87
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值