/**
* 向指定 URL 發送POST方法的請求
*
* @param url
* 發送請求的 URL
* @param param
* 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結果
*/
public static String sendPost(String url, String param, Map<String, String> header) {
PrintWriter out = null;
BufferedReader in = null;
URLConnection conn = null;
StringBuilder jsonStr = new StringBuilder();
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
conn = realUrl.openConnection();
conn.setConnectTimeout(20000);
conn.setRequestProperty("Content-length", String.valueOf(param.length()));
//添加header信息
if(header!=null){
for (Map.Entry<String, String> entry : header.entrySet()) {
conn.setRequestProperty(entry.getKey(),entry.getValue());
}
}
else
{
// 設置通用的請求屬性
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
}
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數body
out.write(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
InputStreamReader reader = new InputStreamReader(conn.getInputStream(), ConstantUtil.UTF_CODE);
char[] buff = new char[1024];
int length = 0;
while ((length = reader.read(buff)) != -1) {
String result = new String(buff, 0, length);
jsonStr.append(result);
}
} catch (Exception e) {
System.out.println("發送 POST 請求出現異常!"+e);
e.printStackTrace();
}
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
System.out.println("特來電返回結果:" + jsonStr.toString());
return jsonStr.toString();
}