昨天遇到一個問題java
就是在接收post請求的時候擷取不到請求資料,本身用ajax寫的時候沒有問題ajax
這個是封包内容json
{"type":"WNING_INFO","code":"WYC","downtime":"2017-01-0101:00:00","busicode":"2017021212123456","data":{"equipment_id":"1","equipment_name":"1号度計","equipment_type":"","type":"SECOND","status":"異常","warn_infor":"設障斷電","location_code":"01010101","company_id":"101","company_name":"","item_code":"000001","item_name":"大米","car_no":""}}浏覽器
這段封包用ajax就可發送過去app
data中就是這段資料post

可能由于是在背景發起的post的請求是以可能跟浏覽器端的請求有所差別,但我到如今也沒有找到差別在哪ui
這段代碼就是發送post請求的方法url
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連結
URLConnection conn = realUrl.openConnection();
// 設定通用的請求屬性
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestProperty("charset", "utf-8");
// 發送POST請求必須設定以下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 擷取URLConnection對象對應的輸出流
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
// 發送請求參數
out.print(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(line);
} catch (Exception e) {
System.out.println("發送 POST 請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
是以就先貼出來我解決這個問題的方式3d
由于資料歸根到底仍是以資料流的方式發送過來的,是以就用流的方式來處理資料code
這段代碼就是擷取HttpServletRequest中的請求資料,并解析
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try{
reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line);
}
} catch (IOException e){
e.printStackTrace();
} finally {
try{
if (null != reader){ reader.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
System.out.println("json;"+sb.toString());
最後獲得的就是一個json字元串
獲得這個json之後直接用Gson解析就行。
但願能幫助到遇見這個問題的人,一樣也但願有人能給我解釋一下出現這個問題的具體緣由,謝謝