java调用第三方http请求接口(个人笔记)
第一步
public Object jysqselectpzxx(QueryFilter queryFilter) {
//一堆传参
Map<String, Object> params = queryFilter.getParams();
JSONObject jsonObject =new JSONObject();
jsonObject.put("page",queryFilter.getPage().getPageNo());
jsonObject.put("limit",queryFilter.getPage().getPageSize());
jsonObject.put("applynum",params.get("applyNum"));
jsonObject.put("varietyname",params.get("varietyName"));
Map<String, Object> param= new HashMap<String, Object>();
param.put("param",jsonObject);
try {
//java调用第三方http请求接口
//重点代码
String s = HttpClientUtils.ajaxPost("你的第三方请求地址url", param);//param参数
JSONObject o = JSONObject.parseObject(s);//返回的字符串解析为对象
JysqqdbSelectPzxx jssqselepzxx = JSON.toJavaObject(o,JysqqdbSelectPzxx.class );//对象解析为具体的类
Page<Object> page = new Page();
page.addAll(jssqselepzxx.getData());//查询的列表数据
page.setPageSize(queryFilter.getPage().getPageSize());//每页显示多少条数据
page.setPages(queryFilter.getPage().getPageNo());//第几页
page.setTotal((long)jssqselepzxx.getCount());//数据总条数
return page;
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
第二步引入http请求工具类
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;
/**
*
* @类名 HttpClientUtils
* @简介 http请求工具类
* @创建日期 2017年12月22日 下午2:49:18
* @当前版本 v1.0
*/
public class HttpClientUtils {
/** 日志 **/
private static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);
/** 换行符 **/
private static String enter = System.getProperty("line.separator");
public static String ajaxGet(String url) {
Map<String, String> headers = new HashMap<String, String>();
// 模拟浏览器请求
headers.put("accept", "application/json;charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
return get(url, headers);
}
/**
*
* @方法名 get
* @简介 发送get请求
* @param url 请求路径
* @param headers
* @return
* @创建日期 2017年12月22日 下午3:11:18
* @当前版本 v1.0
*/
public static String get(String url, Map<String, String> headers) {
// 实例化httpclient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 实例化get方法
HttpGet httpget = new HttpGet(url);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpget.addHeader(entry.getKey(), entry.getValue());
}
}
// 请求结果
CloseableHttpResponse response = null;
String content = "";
try {
// 执行get方法
response = httpclient.execute(httpget);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
log.info(enter + "/----------------------------GET请求----------------------------\\" + //
enter + "URL:" + url + //
enter + "结果:" + content + //
enter + "\\----------------------------请求结束----------------------------/");
return content;
}
public static String ajaxPost(String url, Map<String, Object> params) throws ClientProtocolException, IOException {
Map<String, String> headers = new HashMap<String, String>();
// 模拟浏览器请求
headers.put("accept", "application/json;charset=UTF-8");
headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
return sendPost(url, params, headers, null);
}
/**
*
* @方法名 post
* @简介 发送post请求
* @param url 请求路径
* @param params 参数
* @return
* @创建日期 2017年12月22日 下午3:13:35
* @当前版本 v1.0
*/
public static String post(String url, Map<String, String> params) {
//实例化httpClient
CloseableHttpClient httpclient = HttpClients.createDefault();
//实例化post方法
HttpPost httpPost = new HttpPost(url);
//模拟浏览器请求
httpPost.setHeader("accept", "application/json;charset=UTF-8");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//处理参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
String value = params.get(key);
if (value == null || value.equals("null")) {
value = "\"\"";
}
nvps.add(new BasicNameValuePair("" + key + "", value));
}
//结果
CloseableHttpResponse response = null;
String content = "";
try {
//提交的参数
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
//将参数给post方法
httpPost.setEntity(uefEntity);
//执行post方法
response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
log.info(enter + "/----------------------------POST请求----------------------------\\" + //
enter + "URL:" + url + //
enter + "参数:" + JSON.toJSONString(params) + //
enter + "结果:" + content + //
enter + "\\----------------------------请求结束----------------------------/");
return content;
}
/**
* @方法名 sendPost
* @简介 发送post请求
* @param url 请求路径
* @param params 参数
* @return
* @throws IOException
* @throws ClientProtocolException
* @创建日期 2019年2月18日 下午5:45:56
* @当前版本 v1.0
*/
public static String sendPost(String url, Map<String, Object> params, Map<String, String> headers, String charset) throws ClientProtocolException, IOException {
String defaultCharset = StringUtils.isBlank(charset) ? "UTF-8" : charset;
// 实例化httpClient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 实例化post方法
HttpPost httpPost = new HttpPost(url);
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// 模拟浏览器请求
// httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
// 处理参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
Object value = params.get(key);
if (StringUtils.isNotBlank(key) && value != null)
nvps.add(new BasicNameValuePair(key, value.toString()));
}
// 结果
CloseableHttpResponse response = null;
// 提交的参数
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, defaultCharset);
// 将参数给post方法
httpPost.setEntity(uefEntity);
// 执行post方法
response = httpclient.execute(httpPost);
String content = "";
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), defaultCharset);
return content;
}
log.info(enter + "/----------------------------POST请求----------------------------\\" + //
enter + "URL:" + url + //
enter + "参数:" + JSON.toJSONString(params) + //
enter + "结果:" + content + //
enter + "\\----------------------------请求结束----------------------------/");
return "执行请求失败";
}
/**
*
* @方法名 post
* @简介 发送post请求
* @param url 请求路径
* @param params 参数
* @return
* @创建日期 2017年12月22日 下午3:13:35
* @当前版本 v1.0
*/
public static String sendAjaxPost(String url, String params) {
String charset = "UTF-8";
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json;charset=" + "UTF-8");
return sendPost(url, params, charset, headers);
}
/**
*
* @方法名 post
* @简介 发送post请求
* @param url 请求路径
* @param params 参数
* @return
* @创建日期 2017年12月22日 下午3:13:35
* @当前版本 v1.0
*/
public static String sendPost(String url, String params, String charset, Map<String, String> headers) {
if (StringUtils.isBlank(charset) || "NULL".equalsIgnoreCase(charset))
charset = "UTF-8";
// String charset = "UTF-8";
// 实例化httpClient
CloseableHttpClient httpclient = HttpClients.createDefault();
// 实例化post方法
HttpPost httpPost = new HttpPost(url);
// 模拟浏览器请求
// httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// 结果
CloseableHttpResponse response = null;
String content = "";
try {
StringEntity entity = new StringEntity(params, charset);
entity.setContentEncoding(charset);
entity.setContentType("application/json");
// 将参数给post方法
httpPost.setEntity(entity);
// 执行post方法
response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
content = EntityUtils.toString(response.getEntity(), charset);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
/**
*
* @方法名 fileUpload
* @简介 上传文件
* @param urlStr 上传地址
* @param paths 文件路径数组
* @param inputName 文件名(相当于页面input框的name)
* @return
* @创建日期 2018年7月4日 上午10:33:44
* @当前版本 v1.0
*/
public static String fileUpload(String urlStr, String[] paths, String inputName) {
String res = "";
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String BOUNDARY = "---------------------------123821742118716";
try {
// 设置请求参数
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 获取输出流
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 把文件循环添加到流中
if (paths != null) {
for (int i = 0; i < paths.length; i++) {
String inputValue = paths[i];
if (inputValue == null) {
continue;
}
File file = new File(inputValue);
String filename = file.getName();
String contentType = new MimetypesFileTypeMap().getContentType(file);
if (filename.endsWith(".png")) {
contentType = "image/png";
}
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 数据返回
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
/**
*
* @方法名 fileUpload
* @简介 上传文件
* @param urlStr 上传地址
* @param inputName 相当于页面input框的name
* @param is 文件输入流
* @param filename 文件名
* @param contentType 文件类型
* @return
* @创建日期 2018年7月19日 上午9:48:23
* @当前版本 v1.0
*/
public static String fileUpload(String urlStr, InputStream is, String filename, String contentType, String inputName) {
String res = "";
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String BOUNDARY = "---------------------------123821742118716";
try {
// 设置请求参数
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 获取输出流
OutputStream out = new DataOutputStream(conn.getOutputStream());
if (is != null) {
if (filename.endsWith(".png")) {
contentType = "image/png";
}
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(is);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 数据返回
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
/**
*
* @方法名 fileUpload
* @简介 图像管理系统存储数据
* @param urlStr
* @param is
* @param filename
* @param contentType
* @param inputName
* @param alumnId
* @param userCode
* @retur
* @当前版本 v1.0
*/
public static String fileUpload(String urlStr, InputStream is, String filename, String contentType, String inputName,Integer alumnId,Integer userCode) {
String res = "";
HttpURLConnection conn = null;
// boundary就是request头和上传文件内容的分隔符
String BOUNDARY = "---------------------------123821742118716";
try {
// 设置请求参数
urlStr=urlStr+"?alumnId="+alumnId+"&userCode="+userCode;
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 获取输出流
OutputStream out = new DataOutputStream(conn.getOutputStream());
if (is != null) {
if (filename.endsWith(".png")) {
contentType = "image/png";
}
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
filename = URLEncoder.encode(filename, "utf-8");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(is);
int bytes = 0;
byte[] bufferOut = new byte[10];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 数据返回
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
}