目录
网上的调用方法实例千奇百怪,以下为本人自己整理的Java调用rest接口方法实例,包含get请求和post请求,可创建工具类方便调用,其中get、post请求解决了入出参中文乱码问题。
1、HttpURLConnection 调用
get方式请求
//get方式请求
public String restCallerGet(String path, String param) {
//path 接口路径 xxx/xxx/xxx
//param 入参 ?xxx=x&xxx=x&xxx=x
//接口ip
String httpip = "http://127.0.0.1:8080";
String data = "";
//url拼接
String lasturl = httpip + path + param;
try{
URL url = new URL(lasturl);
//打开和url之间的连接
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//请求头
urlConn.setRequestProperty("Accept-Charset", "utf-8");
urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestMethod("GET");//GET和POST必须全大写
urlConn.connect();
int code = urlConn.getResponseCode();//获得响应码
if(code == 200) {//响应成功,获得响应的数据
//InputStream is = urlConn.getInputStream();//得到数据流(输入流)
//byte[] buffer = new byte[1024];
//int length = 0;
//while ((length = is.read(buffer)) != -1) {
// String res = new String(buffer, 0, length);
// data += res;
//}
//System.out.println(data);
//解决中文乱码
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"UTF-8"));
//data = reader.readLine();
//解决返回参数换行问题,一次读一行,读入null时文件结束
int line = 1;
String tempString = null;
while ((tempString = reader.readLine()) != null) {
data += tempString;
//把当前行号显示出来
//System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
}
urlConn.disconnect(); //断开连接
}catch (Exception e) {
e.printStackTrace();
}
return data;
}
post方式请求
//post方式请求
public String restCallerPost(String path, String param) {
//path 接口路径 xxx/xxx/xxx
//param 入参json {}
//接口ip
String httpip = "http://127.0.0.1:8080";
int responseCode;
//String urlParam = "?aaa=1&bbb=2";
String urlParam = "";
String data = "";
//url拼接
String lasturl = httpip + path + urlParam;
try {
URL restURL = new URL(lasturl);
HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
conn.setRequestMethod("POST");
//请求头
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setDoOutput(true);
//输入流
//OutputStream os = conn.getOutputStream();
//解决中文乱码
OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
os.write(param);
os.flush();
// 输出response code
responseCode = conn.getResponseCode();
// 输出response
if(responseCode == 200){
//输出流
//BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//解决中文乱码
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
//data = reader.readLine();
//解决返回参数换行问题,一次读一行,读入null时文件结束
int line = 1;
String tempString = null;
while ((tempString = reader.readLine()) != null) {
data += tempString;
//把当前行号显示出来
//System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} else {
data = "false";
}
// 断开连接
os.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
main方法调用测试
public static void main(String[] args) {
// TODO Auto-generated method stub
//接口路径
String pathGet = "/xxx/xxx/getFunction";
String pathPost = "/xxx/xxx/postFunction";
//get
String paramGet = "?aaa=1&bbb=2";
//RestCallerUtil为自行封装的工具类
RestCallerUtil rcuGet = new RestCallerUtil();
String resultDataGet = rcuGet.restCallerGet(pathGet, paramGet);
System.out.println(resultDataGet);
//post
String paramPost = "{'aaa':'1','bbb':'2'}";
//RestCallerUtil为自行封装的工具类
RestCallerUtil rcuPost = new RestCallerUtil();
String resultDataPost = rcuPost.restCallerPost(pathPost, paramPost);
System.out.println(resultDataPost);
}
2、RestTemplate 调用
RestTemplate是spring的工具类,常用于spring boot工程用来调用rest接口,如果项目不是spring项目需引入spring-web包才能使用。
get方式请求方法和post类似,以下仅展示post方式请求部分代码参考,get方式调用将 restTemplate.postForEntity 方法变更为 getForEntity 即可。
post方式请求
RestTemplate restTemplate = new RestTemplate();
// 出参构造
// import com.alibaba.fastjson.JSONObject;
JSONObject resultJson = new JSONObject();
String result = null;
// 调用接口url
String url = "http://127.0.0.1:8080/xxx/xxx/postFunction";
// 入参JSON
// import com.alibaba.fastjson.JSONObject;
// String转JSON
JSONObject reqJson = JSONObject.parseObject("{JSON串}");
// 调用
try {
HttpHeaders httpHeaders = new HttpHeaders();
// 指定请求头格式为JSON
httpHeaders.add("Transfer-Encoding", "chunked");
httpHeaders.add("Content-type", "application/json;charset=UTF-8");
HttpEntity<Map> requestEntity = new HttpEntity<>(reqJson, httpHeaders);
// post方式调用
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
result = responseEntity.getBody();
// String转JSON
resultJson = JSONObject.parseObject(result);
return resultJson;
} catch (Exception e) {
// 异常处理
}