Using Specific Data from POST in Java

87 views Asked by At

Using POST to www.httpbin.org/post (to test the POST function) with the input of "Hello World!", I get the response of:

{
  "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

Based on this, I know that the POST is functioning.. Now I want to just take the input from the form variable and get a string of Hello World!.

I'm trying to use JSON to parse it, but am running into issues... What would be the way to get the Hello World! from the form variable?

POST Code:

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());

The getString("data") is what is giving me issues... I have noticed if I send the text "data" through the POST method, the program seems to work fine, or else it would crash with an error saying that JSON Object does not exist.

1

There are 1 answers

0
Dmitrii Semenov On BEST ANSWER

The problem is a wrong Header "Content-Type": "application/x-www-form-urlencoded" that you provide in the request. You declare that you send the form data, however you send plain text in the Body. Server is trying to parse your request, and provide you parsed information.

If you provide the right Mime-Type "Content-Type": "text/plain", you get something like:

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

And then you can get what you want by the code you wanted to use: getString("data")