JAVA调用restful接口
目前随着互联网微服务的兴起,需要通过接口进行服务的传输情况越来越多,原始的webservice相对较为臃肿,常见代表为aix2,xfire等等。新兴的则以restfull标准接口为代表的例如httpUrlConnection,okhttpclient,Unirest为代表。
首先先介绍一下httpurlconnection
本对象为JDK原生支持方法,不用引入任何第三方依赖包。具体代码如下:
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
OutputStreamWriter out = null;
try {//注意这里因为请求了spring发布的接口都是以html结尾的。
URL realUrl = new URL(url+".html");
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.4620.400 QQBrowser/9.7.13014.400");
connection.setDoOutput(true);
connection.setDoInput(true);
out = new OutputStreamWriter(connection.getOutputStream(),"utf-8");
// 发送请求参数
out.write("param="+param);
// flush输出流的缓冲
out.flush();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
接下来介绍一下okhhtp
使用okhttp首先要引入依赖包,pom资源库增加
<!-- http请求接口 -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.6.0</version>
</dependency>
接下来我们看JAVA代码:
public static String send(String url, String param) {
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder().url(WEB_URL + url + "?" + param).method("POST", body).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {// 请求成功
return response.body().string();
} else {
return "";
}
}catch (IOException e) {//接口请求异常-直接返回空
e.printStackTrace();
return "";
}
}
对比一下第一个更像是通过浏览器抓包给的数据接口的发那个是,尤其对conn.set各种属性,第二个封装的较为简洁,第二个也是Postman推荐的java代码的使用方式。
上面代码占到ide就能执行,不想动手复制的,也可以直接到这里去下载:
https://download.youkuaiyun.com/download/Himly_Zhang/12440433