java
/**
* 远程post请求
*
* @param urlStr
* @param param
* @return
*/
public static String doPost(String urlStr, String param,String clientId,String authorization) {
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.setRequestProperty("clientId", clientId); //登录认证
connection.setRequestProperty("authorization", authorization); //登录认证
connection.setConnectTimeout(90000); //30秒连接超时
connection.setReadTimeout(90000); //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();
}
调用示例:
java
Map<String, Object> personInfoMap = new HashMap<>();
personInfoMap.put("xxx", "");
String params = JSONObject.toJSONString(personInfoMap);
//调用接口发送数据
String jsonStr = BeanUtiles.doPost(urlStr, params, clientId, authorization);
//处理返回信息
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
Integer code = jsonObject.getInteger("code");
String msg = jsonObject.getString("msg");
if (code == 200) {
//调用成功
String returnData= jsonObject.getString("data");
} else {
//调用失败
}