主要代码
/**
* 过期时间
*/
private static int connectTimeout = 60000;
private static int readTimeout = 60000;
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param jsonParameter 请求参数,请求参数体 应该是 json {"":""} 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendJsonPostUTF8(String url, String jsonParameter) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json");
conn.setUseCaches(false);
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
// 发送请求参数
out.print(jsonParameter);
// flush输出流的缓冲
out.flush();
if (conn.getResponseCode() == 200) {
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} else {
in = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
String errorResult = "";
String line;
while ((line = in.readLine()) != null) {
errorResult += line;
}
return errorResult;
}
} catch (Exception e) {
e.printStackTrace();
result.append("{\"error\":\"" + e.getMessage() + "\"}");
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
result.append("{\"error\":\"" + ex.getMessage() + "\"}");
}
}
return result.toString();
}
调用方式
HashMap<String, Object> configs = new HashMap<>();
configs.put("url", "http://10.66.150.35:8880/api/operation/billing2?param=all");
String json = RequestClient.sendJsonPostUTF8("http://10.70.24.129:8888/scans", JSONObject.toJSON(configs).toString());
System.out.println(json);
//将String转换为jsonObject对象
JSONObject a = JSONObject.parseObject(json);