一,通过JDK网络类Java.net.HttpURLConnection
使用步骤:
1、通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)。
2、设置请求的参数。
3、发送请求。
4、以输入流的形式获取返回内容。
5、关闭输入流。
public String sendByPost(String path, String postContent, String authorization) {
HttpURLConnection httpURLConnection = null;
BufferedWriter writer = null;
BufferedReader reader = null;
try {
URL url = new URL(path);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(20 * 60 * 1000);
httpURLConnection.setReadTimeout(20 * 60 * 1000);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
httpURLConnection.setRequestProperty("Access-Token", authorization);
writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
writer.write(postContent);
writer.flush();
int httpRspCode = httpURLConnection.getResponseCode();
InputStream inputStream = (httpRspCode == 200)
? httpURLConnection.getInputStream()
: httpURLConnection.getErrorStream();
reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (writer != null) writer.close();
if (reader != null) reader.close();
if (httpURLConnection != null) httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
二,Spring提供的RestTemplate
1、在项目启动类中添加RestTemplate 的bean,后续就可以在代码中@Autowired引入。
@SpringBootApplication
@MapperScan("com.xxx.xxx.mapper")
public class RiskApplication {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RiskApplication.class, args);
}
}
@Autowired
private RestTemplate restTemplate;
/**
* post 请求 参数在 request里;
* @param url, request
* @return string
*/
public String doPostRequest(String url, String request,String authorization){
URI uri = UriComponentsBuilder.fromUriString(url).build().toUri();
// 假如 request 已经是 JSON 字符串,无需再次转换
// String requestStr= JSONObject.toJSONString(request);
String requestStr = request; // 直接使用 request
log.info("请求接口:{}, 请求报文:{}", url, requestStr);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// headers.set("Access-Token", authorization);
HttpEntity<String> httpEntity = new HttpEntity<>(requestStr, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);
if (responseEntity == null) {
return null;
}
String seqResult = "";
try {
if(responseEntity.getBody() != null ) {
seqResult = responseEntity.getBody();
}
log.info("返回报文:{}", seqResult);
} catch (Exception e) {
log.error("接口返回异常", e);
}
return seqResult;
}