当前位置: 首页 > >

OkHttp访问RESTful Webservice接口

发布时间:

下载okHttp相关的jar包:?https://download.csdn.net/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 map = new HashMap();
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 map = new HashMap();
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;
}

?


?


?



友情链接: