OkHttp訪問RESTful Webservice介面
阿新 • • 發佈:2019-02-07
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; }