发送的是request payload格式请求 普通post请求不建议调用
private static String postJsonFile1(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String encoding, HttpMethod method) {
JSONObject jsonObject = JSONObject.fromObject(params);
URL uUrl = null;
HttpURLConnection conn = null;
BufferedWriter out = null;
BufferedReader in = null;
try {
//创建和初始化连接
uUrl = new URL(url);
conn = (HttpURLConnection) uUrl.openConnection();
conn.setRequestProperty("content-type", "application/json");
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));
}
}
out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), encoding));
out.write(jsonObject.toString());
out.flush();
//接收返回结果
StringBuilder result = new StringBuilder();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
if (in != null) {
String line = "";
while ((line = in.readLine()) != null) {
result.append(line);
}
}
return result.toString();
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
//处理错误流,提高http连接被重用的几率
try {
byte[] buf = new byte[100];
InputStream es = conn.getErrorStream();
if (es != null) {
while (es.read(buf) > 0) {
;
}
es.close();
}
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
//关闭连接
if (conn != null) {
conn.disconnect();
}
}
return null;
}
调用方法
public static String getBlockHeight(){
Map map=new HashMap();
map.put("demo","demo");
String str=postJsonFile1("http://www.baidu.com", map, null, 1500, 1500, "UTF-8",HttpMethod.POST);
JSONObject myJson = JSONObject.fromObject(str);
}