1. 程式人生 > >java傳送post請求以json陣列形式

java傳送post請求以json陣列形式

public static void dspDaoRu(DspNews dspNews) throws Exception {
String result = "";
// 新增url引數
Map<String, Object> map = new HashMap<String, Object>();
// JSONObject obj = new JSONObject();
map.put("name", dspNews.getName());
map.put("sex", "0");
map.put("phone", dspNews.getMobile());
map.put("customerSource", QuDao.getNameByValue(dspNews.getFromWeb()));// 渠道
map.put("belongProvince", dspNews.getProvince());// 首先做判斷
map.put("belongCity", dspNews.getCity());// 城市
map.put("adCode", dspNews.getDspNumber() + "-" + dspNews.getAdGroup() + "-" + dspNews.getPageNumber());// 頁面廣告組創意
map.put("customerSituation", "無");// 客戶情況

JSONArray json = JSONArray.fromObject(map);

                //列印格式樣式

System.err.println( json.toString());
sendPostUrlTwo(URL, json.toString());

}

public static JSONObject sendPostUrlTwo(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
JSONObject jsonObject = null;
String result = "";
try {
URL realUrl = new URL(url);
// 開啟和URL之間的連線
URLConnection conn = realUrl.openConnection();
// 傳送POST請求必須設定如下兩行
conn.setDoOutput(true);

conn.setDoInput(true);

conn.setRequestProperty("token", token);//設定請求頭所需token驗證
conn.setRequestProperty("Content-Type", "application/json");
// 獲取URLConnection物件對應的輸出流(設定請求編碼為UTF-8)
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
System.err.println(out);
// 傳送請求引數
out.print(param);
// flush輸出流的緩衝
out.flush();
// 獲取請求返回資料(設定返回資料編碼為UTF-8)
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.err.println(result);//列印返回結果   
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}


return jsonObject;

}

//如果提交的時候報500錯誤,需要檢查提交的json格式,和提交欄位,是否與介面一致!