2015-06-23 64 views
2

使用特定數據使用POST到www.httpbin.org/post(測試POST函數)的輸入,我得到的迴應:從POST在Java中

{ 
    "args": {}, 
    "data": "", 
    "files": {}, 
    "form": { 
    "Hello World!": "" 
    }, 
    "headers": { 
    "Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", 
    "Content-Length": "12", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)" 
    }, 
    "json": null, 
    "origin": "98.164.222.196", 
    "url": "http://httpbin.org/post" 
} 

Resp Code:200 
Resp Message:OK 

基於此,我知道POST正在運行..現在我想從form變量中獲取輸入並獲取一串Hello World!

我試圖用JSON解析它,但遇到問題...將從form變量中獲得Hello World!變量的方法是什麼?

郵編:

String httpURL = "http://httpbin.org/post"; 

String query = textInput; 

URL myurl = new URL(httpURL); 
HttpURLConnection con = (HttpURLConnection)myurl.openConnection(); 
con.setRequestMethod("POST"); 

con.setRequestProperty("Content-length", String.valueOf(query.length())); 
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)"); 
con.setDoOutput(true); 
con.setDoInput(true); 

DataOutputStream output = new DataOutputStream(con.getOutputStream()); 


output.writeBytes(query); 

output.close(); 

DataInputStream input = new DataInputStream(con.getInputStream()); 


for(int c = input.read(); c != -1; c = input.read()) 
{ 
    response += (char)c; 
} 

input.close(); 

System.out.println("" + response); 

//JSONObject json = new JSONObject(response); 
//String uname = json.getJSONObject("form").getString("data"); 

System.out.println("Resp Code:"+con .getResponseCode()); 
System.out.println("Resp Message:"+ con .getResponseMessage()); 

getString("data")是什麼給我的問題......如果我通過POST方法來發送文本「數據」我注意到,該方案似乎做工精細,否則會崩潰,並顯示JSON對象不存在的錯誤。

回答

1

問題是你在請求中提供了一個錯誤的頭文件「Content-Type」:「application/x-www-form-urlencoded」。您聲明您發送表單數據,但是您在主體中發送純文本。服務器試圖解析你的請求,並提供你解析的信息。

如果提供正確的MIME類型「內容類型」:「text/plain的」,你喜歡的東西:

{ 
    "args": {} 
    "data": "Hello world!" 
    "files": {} 
    "form": {} 
    "headers": { .... 

然後你就可以通過代碼你得到你想要的東西想要使用:getString(「data」)