第一种:需要httpclient的依赖包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
代码:
public static String callBgrsjk(String requestParams) {
String url = "url地址";
Map<String,Object>jb=new HashMap();
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(300000)
.setConnectTimeout(300000)
.build();
HttpPost post = new HttpPost(url);
post.setConfig(requestConfig);
post.setHeader("Content-Type","application/json;charset=utf-8");
StringEntity postString = new StringEntity(requestParams,"utf-8");
post.setEntity(postString);
HttpResponse response = httpClient.execute(post);
String content = EntityUtils.toString(response.getEntity());
return content;
} catch (Exception e) {
log.error("调用DataService接口失败,url:" + url + ",参数:" + requestParams, e);
}
}
第二种:使用jdk中的URL
public static byte[] download(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String encoding, HttpMethod method) {
//构造请求参数字符串
StringBuilder paramsStr = null;
if (params != null) {
paramsStr = new StringBuilder();
Set<Map.Entry> entries = params.entrySet();
for (Map.Entry entry : entries) {
String value = (entry.getValue() != null) ? (String.valueOf(entry.getValue())) : "";
paramsStr.append(entry.getKey() + "=" + value + "&");
}
//只有POST方法才能通过OutputStream(即form的形式)提交参数
if (method != HttpMethod.POST) {
try {
url += "?" + paramsStr.toString().replace(" ", "%20");
} catch (Exception e) {
}
}
}
URL uUrl = null;
HttpURLConnection conn = null;
BufferedWriter out = null;
BufferedReader in = null;
try {
//创建和初始化连接
URI uri = new URI(url);
uUrl = new URL(uri.toASCIIString());
conn = (HttpURLConnection) uUrl.openConnection();
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
conn.setRequestMethod(method.toString());
conn.setDoOutput(true);
conn.setDoInput(true);
//设置连接超时时间
conn.setConnectTimeout(connectTimeout);
//设置读取超时时间
conn.setReadTimeout(readTimeout);
//指定请求header参数
if (headers != null && headers.size() > 0) {
Set<String> headerSet = headers.keySet();
for (String key : headerSet) {
conn.setRequestProperty(key, headers.get(key));
}
}
if (paramsStr != null && method == HttpMethod.POST) {
//发送请求参数
out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), encoding));
out.write(paramsStr.toString());
out.flush();
}
return readInputStream(conn.getInputStream());
} catch (Exception e) {
log.error("调用接口[" + url + "]失败!请求URL:" + url + ",参数:" + params, e);
throw new ReportException(ResponseCode.CODE_FAILED, "can't download file");
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
log.error("out close exception", e);
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error("out close exception", e);
}
}
//关闭连接
if (conn != null) {
conn.disconnect();
}
}
}
第三种(没用过)
public static String sendPost(String params, String requestUrl,
String authorization) throws IOException {
byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为二进制流
HttpClient httpClient = new HttpClient();// 客户端实例化
PostMethod postMethod = new PostMethod(requestUrl);
//设置请求头Authorization
//postMethod.setRequestHeader("Authorization", "Basic " + authorization);
// 设置请求头 Content-Type
postMethod.setRequestHeader("Content-Type", "application/json");
InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
requestBytes.length);
RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
requestBytes.length, "application/json; charset=utf-8"); // 请求体
postMethod.setRequestEntity(requestEntity);
httpClient.executeMethod(postMethod);// 执行请求
InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
byte[] datas = null;
try {
datas = readInputStream(soapResponseStream);// 从输入流中读取数据
} catch (Exception e) {
e.printStackTrace();
}
String result = new String(datas, "UTF-8");// 将二进制流转为String
// 打印返回结果
// System.out.println(result);
return result;
}
参考:
https://www.cnblogs.com/feiyangbahu/p/9640261.html