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對象不存在的錯誤。