OkHttp访问RESTful Webservice接口

本文介绍如何利用OkHttp访问RESTful Web Service接口。在操作中,需注意可能遇到的返回值类型问题,如出现从response.body().string()获取数据异常时,可以改用responseBody.byteStream()转换为字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下载okHttp相关的jar包: https://download.youkuaiyun.com/download/qq_37160920/10576350

package com.cn.controller;



import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class getUser {

    public static void main(String[] args) throws Exception {
        getByOKHTTP();
    }


    public static  void getByOKHTTP() throws IOException{

        String url = "";
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");

        //设置参数
        Map<String,String> map = new HashMap<String,String>();
        map.put("code","");
        map.put("name","");
        String content =JSONObject.toJSON(map).toString();
        RequestBody body = RequestBody.create(mediaType,content);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();

        try {
           Response response = client.newCall(request).execute();
            
           //直接获取返回的数据
           String result = response.body().string();
           System.out.println(result);

        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

根据接口的返回值类型问题,可能会出现 response.body().string()获取数据时异常. 可以先获取responseBody.byteStream(),再把流转成string

 public static  void getByOKHTTP() throws IOException{

        String url = "";
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");

        Map<String,String> map = new HashMap<String,String>();
        map.put("code","");
        map.put("name","");
   
        String content =JSONObject.toJSON(map).toString();
        RequestBody body = RequestBody.create(mediaType,content);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();

        try {
           Response response = client.newCall(request).execute();
           ResponseBody responseBody  =response.body();
           InputStream inputStream  = responseBody.byteStream();
           byte[] bytes =   readInputStream(inputStream);
           String data = new String(bytes);

           System.out.println(data);


        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public  static byte[] readInputStream(InputStream inputStream) throws  IOException{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(buffer)) !=-1){
                outputStream.write(buffer,0,len);
            }
        }catch (IOException e){
//            e.printStackTrace();
        }
        byte[] data = outputStream.toByteArray();
        outputStream.close();
        inputStream.close();
        return data;
    }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值