/**
* 发送post请求
*
* @param baseUrl
* @param paramMap
* @param mediaType
* @param headers
* @param json
* @return
*/
private String doPost(String baseUrl, Map<String, String> paramMap, String mediaType,
Map<String, String> headers, String json) throws Exception {
HttpURLConnection urlConnection = null;
InputStream in = null;
OutputStream out = null;
BufferedReader bufferedReader = null;
String result = null;
try {
StringBuffer sb = new StringBuffer();
sb.append(baseUrl);
if (paramMap != null) {
sb.append("?");
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value).append("&");
}
baseUrl = sb.toString().substring(0, sb.toString().length() - 1);
}
URL urlObj = new URL(baseUrl);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setConnectTimeout(50000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.addRequestProperty("content-type", mediaType);
if (headers != null) {
for (String key : headers.keySet()) {
urlConnection.addRequestProperty(key, headers.get(key));
}
}
out = urlConnection.getOutputStream();
out.write(json.getBytes("utf-8"));
out.flush();
int resCode = urlConnection.getResponseCode();
System.out.println("状态码::" + resCode);
// if (resCode == HttpURLConnection.HTTP_OK || resCode == HttpURLConnection.HTTP_CREATED || resCode == HttpURLConnection.HTTP_ACCEPTED) {
in = urlConnection.getInputStream();
// } else {
// in = urlConnection.getErrorStream();
// }
bufferedReader = new BufferedReader(new InputStreamReader(in, "utf-8"));
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
String ecod = urlConnection.getContentEncoding();
if (ecod == null) {
ecod = Charset.forName("utf-8").name();
}
result = new String(temp.toString().getBytes("utf-8"), ecod);
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
throw e;
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
urlConnection.disconnect();
}
return result;
}
版权声明:本文为weixin_55075245原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。