端午安康!
由于导师和校外企业的具体需求,我手上的项目需要融合某企业 API 的接口,因此,要我加急做一个版本出来。项目整体使用了 SpringCloud + Vue 微服务框架,后端简单处理前端的请求数据后,将请求代理转发至企业开放的 API,在收到企业 API 响应数据后,处理后返回前端。
明确了需求后,决定在后端对应的服务中,封装一个 HTTP 请求类,以统一地处理各种请求。
// RequestService 文件
// 已做了必要的匿名处理
package com.***.service;
import com.alibaba.fastjson.JSONObject;
public interface RequestService {
// 接口参数示例:
// url: /stories
// param: workspace_id=01010101&id=1111222233334444
JSONObject getGitCodeRequest(String url, String param);
JSONObject postGitCodeRequest(String url, String param);
JSONObject putGitCodeRequest(String url, String param);
JSONObject deleteGitCodeRequest(String url, String param);
}
RequestService 文件中封装了常用的四种 HTTP 请求 Methods(GET/POST/PUT/DELETE)。接下来看具体的实现类。
// RequestServiceImpl 文件
// 已做了必要的匿名处理
package com.***.impl;
import com.alibaba.fastjson.JSONObject;
import com.***.service.RequestService;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
@Service
public class RequestServiceImpl implements RequestService {
private JSONObject getHttpConnect(String url) {
JSONObject json = null;
try {
// 1. 得到访问地址的URL
URL httpUrl = new URL(url);
// 2. 得到网络访问对象java.net.HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
/* 3. 设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 */
// 设置是否向HttpURLConnection输出
connection.setDoOutput(true);
// 设置是否从httpUrlConnection读入
connection.setDoInput(true);
// 设置请求方式
connection.setRequestMethod("GET");
// 设置是否使用缓存
connection.setUseCaches(true);
// 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setInstanceFollowRedirects(true);
// 设置超时时间
connection.setConnectTimeout(3000);
// 连接
connection.connect();
// 4. 得到响应状态码的返回值 responseCode
int code = connection.getResponseCode();
// 5. 如果返回值正常,数据在网络中是以流的形式得到服务端返回的数据
String msg = "";
if (code == 200) { // 正常响应
// 从流中读取响应信息
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) { // 循环从流中读取
msg += line + "\n";
}
reader.close(); // 关闭流
}
// 6. 断开连接,释放资源
connection.disconnect();
json = JSONObject.parseObject(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
private JSONObject postHttpConnect(String url, String body) {
JSONObject json = null;
try {
// 1. 得到访问地址的URL
URL httpUrl = new URL(url);
// 2. 得到网络访问对象java.net.HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
/* 3. 设置请求参数(过期时间,输入、输出流、访问方式),以流的形式进行连接 */
// 设置请求方式
connection.setRequestMethod("POST");
// 设置是否向HttpURLConnection输出
connection.setDoOutput(true);
// 设置是否从httpUrlConnection读入
connection.setDoInput(true);
// 设置是否使用缓存
connection.setUseCaches(false);
//设置参数类型是json格式
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
// 设置超时时间
connection.setConnectTimeout(3000);
// 连接
connection.connect();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(body);
writer.close();
// 4. 得到响应状态码的返回值 responseCode
int code = connection.getResponseCode();
// 5. 如果返回值正常,数据在网络中是以流的形式得到服务端返回的数据
String msg = "";
if (code == 200) { // 正常响应
// 从流中读取响应信息
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) { // 循环从流中读取
msg += line + "\n";
}
reader.close(); // 关闭流
}
// 6. 断开连接,释放资源
connection.disconnect();
json = JSONObject.parseObject(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
@Override
public JSONObject getGitCodeRequest(String url, String param) {
JSONObject json = null;
String urlNameString = "";
if(param == null)
urlNameString = "https://fakename.com" + url + "?private_token=thisisfakeprivatetoken";
else
urlNameString = "https://fakename.com" + url + "?private_token=thisisfakeprivatetoken&" + param;
json = getHttpConnect(urlNameString);
return json;
}
@Override
public JSONObject postGitCodeRequest(String url, String param) {
JSONObject json = null;
String urlNameString = "";
urlNameString = "https://fakename.com" + url + "?private_token=thisisfakeprivatetoken";
json = postHttpConnect(urlNameString, param);
return json;
}
// put && delete 同理,不再赘述。
封装完毕,接下来就可以愉快地使用了!
使用这些接口有几个注意事项:
GET
- url 与参数之间用 “?” 隔开;
- 键值对中键与值用 “=” 连接;
- 两个键值对之间用 “&” 连接。
- 请求头的设置务必要放在网络连接(connection.connect();)之前;
POST
- 传递 json 格式数据时需要在请求头中设置参数类型是 json 格式;
- 参数应是 json 格式的字符串;
- 可以通过 HashMap 转 JSONString 的形式构造请求参数体。