一、远程调用post接口时的方法
方法一:
这个方式的querys传的是参数(参数可是单个参数/对象)
host指的是远程调用的主机地址
headers指的是头信息(可有可无)
body指的是字符集的编码格式
public static String doPost(String host, String path,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body!=null && !"".equals(body) && body.length()>0) {
request.setEntity(new StringEntity(body, "utf-8"));
}
//客户端执行。获取数据
HttpResponse response = httpClient.execute(request);
//通过response里的getEntity()方法获取客户端的返回值,然后return进行返回;
HttpEntity entity = (HttpEntity) response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, "UTF-8");
}
//json根据key取value
EntityUtils.consume(entity);
return body;
}
方法二:
urlStr 第三方接口地址
param 数据参数,JSON格式,可以为null(这个一般传的是对象参数)
public static String doPost(String urlStr, String param) {
HttpURLConnection connection = null;
InputStream is = null;
InputStreamReader rsd = null;
BufferedReader br = null;
OutputStream os = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
StringBuffer sb = new StringBuffer();
try {
URL url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false); //不缓存
connection.setRequestProperty("connection", "Keep-Alive"); //设置保活连接
connection.setRequestProperty("charset", "UTF-8"); //提交的数据编码
connection.setRequestProperty("Content-type", "application/json"); //提交的数据格式
connection.setRequestProperty("accept", "application/json"); //接收的数据格式
connection.setConnectTimeout(30000); //30秒连接超时
connection.setReadTimeout(30000); //30秒读取超时
connection.connect();
if (param != null && !"".equals(param)) {
os = connection.getOutputStream();
osw = new OutputStreamWriter(os);
bw = new BufferedWriter(osw);
bw.write(param);
bw.flush();
}
int status = connection.getResponseCode();
if (status == 200) {
is = connection.getInputStream();
rsd = new InputStreamReader(is, "UTF-8");
br = new BufferedReader(rsd);
String s;
while ((s = br.readLine()) != null) {
sb.append(s);
}
} else {
return "{\"ResuleState\":\"-1\",\"Msg\":\"连接异常\"}";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (rsd != null) {
rsd.close();
}
if (is != null) {
is.close();
}
if (bw != null) {
bw.close();
}
if (osw != null) {
osw.close();
}
if (os != null) {
os.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
举例:
Map<String, Object> map = new HashMap<>();
map.put("currentPage",paramData.getCurrentPage());
map.put("pageSize",paramData.getPageSize());
map.put("addrList",paramData.getAddrList());
map.put("startTime",paramData.getStartTime());
map.put("endTime",paramData.getEndTime());
String params = JSONObject.toJSONString(map);
String registerResult = HttpUtils.doPost(base + url, params);
JSONObject result = JSONObject.parseObject(registerResult);
二、远程调用GET时的方法
方法一:
public static String doGet(String url, Map<String, Object> param) {
StringBuffer sb = new StringBuffer(url+"?");
Iterator<Map.Entry<String, Object>> iterator = param.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> entry = iterator.next();
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
sb = sb.deleteCharAt(sb.length() - 1);
log.info("Http-GET 请求:" + sb.toString());
String data = "";
// 创建请求对象
HttpGet httpGet = new HttpGet(sb.toString());
// 设置参数
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
// 执行请求的对象
HttpClient client = new DefaultHttpClient(params);
// 执行请求镀锡
try {
HttpResponse resp = client.execute(httpGet);
// 判断是否响应成功
if (resp.getStatusLine().getStatusCode() == 200) {
// 获取响应 的数据
HttpEntity entity = resp.getEntity();
data = EntityUtils.toString(entity, "utf-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
方法二:
public static String doGet(String host, String path, String method,String encoding,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
String body = "";
// HttpClient httpClient = wrapClient(host);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
response = httpClient.execute(request);
HttpEntity entity = (HttpEntity) response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
//
//json根据key取value
// JSONObject jsonObject = JSONObject.parseObject(body);
// String value = jsonObject.getString("bodyData");
// JSONObject jsonObject1 = JSONObject.parseObject(value);
// String list = jsonObject1.getString("list");
EntityUtils.consume(entity);
response.close();
// System.out.println("数据内容:" + body);
// System.out.println("value:" + list);
return body;
}