Results 1 to 9 of 9
  1. #1
    Join Date
    Jan 2013
    Posts
    69
    Rep Power
    0

    Default HTTP POST request using JSON

    Hi everyone!
    I have to make a http Post request using a JSON string I allready have generated.
    I tried different two different methods :
    1.HttpURLConnection
    2.HttpClient
    but I get the same "unwanted" result from both of them.
    I also have been googling for 3 days to find out any solution but with no success.

    My code so far with HttpURLConnection is:

    Java Code:
        public static void SaveWorkflow() throws IOException {
        		
               URL url = null;
           
               url = new URL(myURLgoeshere);
               
               HttpURLConnection urlConn = null;
              
               urlConn = (HttpURLConnection) url.openConnection();
              
               urlConn.setDoInput (true);
        
               urlConn.setDoOutput (true);
        
               urlConn.setRequestMethod("POST");
               
               urlConn.setRequestProperty("Content-Type", "application/json");
               
               urlConn.connect();
                
               DataOutputStream output = null;
                
               DataInputStream input = null;
        
               output = new DataOutputStream(urlConn.getOutputStream());
         
                /*Construct the POST data.*/
                String content = generatedJSONString;
        
                /* Send the request data.*/
                    output.writeBytes(content);
                    output.flush();
                    output.close();
                    
                /* Get response data.*/
                String response = null;
                    input = new DataInputStream (urlConn.getInputStream());
                    while (null != ((response = input.readLine()))) {
                    System.out.println(response);
                    input.close ();
              }
           }
    My code so far with HttpClient is:


    Java Code:
        public static void SaveWorkflow() {
        		  try {
        			  
        				HttpClient httpClient = new DefaultHttpClient();
        				HttpPost postRequest = new HttpPost(myUrlgoeshere);
        				StringEntity input = new StringEntity(generatedJSONString);
        				input.setContentType("application/json;charset=UTF-8");
        				postRequest.setEntity(input);
        				input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
                        postRequest.setHeader("Accept", "application/json");
                        postRequest.setEntity(input); 
        		 
        				HttpResponse response = httpClient.execute(postRequest);
        		 
        				BufferedReader br = new BufferedReader(
        		                        new InputStreamReader((response.getEntity().getContent())));
        		 
        				String output;
        				
        				while ((output = br.readLine()) != null) {
        					System.out.println(output);
        				}
        		 
        				httpClient.getConnectionManager().shutdown();
        		 
        			  } catch (MalformedURLException e) {
        		 
        				e.printStackTrace();
        		 
        			  } catch (IOException e) {
        		 
        				e.printStackTrace();
        		 
        			  }
        	}
    Where generatedJsonString is the variable that contains my JSON String:
    {"description":"prova_Process","modelgroup":"","mo dified":"false"}

    The response I get is:
    {"response":false,"message":"Error in saving the model. A JSONObject text must begin with '{' at 1 [character 2 line 1]","ids":[]}

    Any idea please?

  2. #2
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: HTTP POST request using JSON

    My first idea would be to actually listen to what the error is telling you because it is not lying. If it is of the opinion that there is actual content before the initial { character, which is clearly against the rule, then you must now assume that it is in fact there and figure out where that is coming from.

    My first question which I would have to research into when I look at the code is: why DataInputStream/DataOutputStream? I would assume you would use a Reader/Writer since this is text data.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  3. #3
    Join Date
    Jan 2013
    Posts
    69
    Rep Power
    0

    Default Re: HTTP POST request using JSON

    I don't think the problem is my Json string, becouse when I put it directly after the url in my web browser, so when I put it like this:
    myURL{"description":"prova_Process","modelgroup":" ","modified":"false"}
    it gives me the message that I want ...
    The problem is when I try to post my Json string through java code with the two methods I've mentioned

  4. #4
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: HTTP POST request using JSON

    The error says there is a problem int he JSON string, so I am going to assume that there is a problem in that JSON string until you prove otherwise. Thinking is not knowing. And that error seems to be referring to completely different data than you experimented with, it is for example referring to an "ids" component if I read it correctly.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  5. #5
    Join Date
    Jan 2013
    Posts
    69
    Rep Power
    0

    Default Re: HTTP POST request using JSON

    I said I tested the JSON string, putting it directly after the url in my web browser and it gives me the correct output.
    The error I get now is the same error as when I go to the given url on my web browser and there is no JSON string after it. HTTP POST request using JSON-1.pngHTTP POST request using JSON-2.png

  6. #6
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,030
    Rep Power
    6

    Default Re: HTTP POST request using JSON

    You can try and dance around the issue as much as you like, but your test only proves that the receiving end works as designed; the json string as generated by your code OR as transmitted by your code is still wrong. Until you make the effort to dive in and go figure out where it is going wrong, you're going to stay stuck.

    Here is another test you can perform: use something like a HTTP sniffer or some sort of browser plugin to log requests to see what request your application is actually sending.


    PS: you say you POST the data to the server, but your test seems to transmit the data as an URL parameter as part of a GET request...
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: HTTP POST request using JSON

    No, what gimbal is suggesting (and the error message is implying) is that isn't the actual string being produced by the code.
    So you need to log that string in the code.
    Simply pasting the String you think your code is creating isn't going to help you solve this.

    As for the DataInputStream, read the API on readLine().
    It's been deprecated for quite some time, and you should be using a BufferedReader (which is explained at that link).
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    Join Date
    Jan 2013
    Posts
    69
    Rep Power
    0

    Default Re: HTTP POST request using JSON

    I tried to build the JsonString again in this way :
    Java Code:
    public static void SaveWorkflow () throws JSONException, ClientProtocolException, IOException{
    		 final String SERVICE_URL = "/delegate/WFD/WFService?";
    	        InputStream inputStream = null;
    	        String result = "";
    	   
    	            HttpClient httpclient = new DefaultHttpClient();
    	 
    	            HttpPost httpPost = new HttpPost("http://192.168.1.10:8080/" + SERVICE_URL + "task=savemodel" + "&code=");
    	 
    	            String json = "";
    	 
    	            JSONObject jsonObject = new JSONObject();
    	            jsonObject.accumulate("description", "prova_Process");
    	            jsonObject.accumulate("modelgroup", "");
    	            jsonObject.accumulate("modified", "false")
    	            
    	            //  convert JSONObject to JSON to String
    	            json = jsonObject.toString();
    	 
    	            //  set json to StringEntity
    	            StringEntity se = new StringEntity(json);
    	 
    	            // set httpPost Entity
    	            httpPost.setEntity(se);
    	 
    	            // inform the server about the type of the content   
    	            httpPost.setHeader("Accept", "application/json");
    	            httpPost.setHeader("Content-type", "application/json");
    	 
    	            //  Execute POST request to the given URL
    	            HttpResponse httpResponse = httpclient.execute(httpPost);
    	 
    	            // receive response as inputStream
    	            inputStream = httpResponse.getEntity().getContent();
    	 
    	          // convert inputstream to string
    	            if(inputStream != null)
    	                result = convertInputStreamToString(inputStream);
    	 
                System.out.println(result);
    	    }
    but I still get the same result :
    {"response":false,"message":"Errore nel salvataggio del modello:\nA JSONObject text must begin with '{' at 1 [character 2 line 1]","ids":[]}

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,014
    Rep Power
    20

    Default Re: HTTP POST request using JSON

    And where are you logging the JSON string?

    At the same time I would take gimbals earlier suggestion and use something like Fiddler2 to look at the request being sent and see if something is being mucked up.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. HttpURLconnection POST request
    By chopficaro in forum Advanced Java
    Replies: 12
    Last Post: 05-21-2012, 02:10 AM
  2. HTTP POST Request (HttpURLConnection)
    By Dude in forum Networking
    Replies: 17
    Last Post: 07-15-2011, 11:11 PM
  3. Web API using JSON/POST
    By atomant in forum New To Java
    Replies: 3
    Last Post: 02-17-2011, 10:56 PM
  4. HTTP Post Request from Java
    By Darrarski in forum New To Java
    Replies: 10
    Last Post: 06-05-2010, 05:22 PM
  5. First post as per request
    By happyknappy in forum Introductions
    Replies: 3
    Last Post: 07-30-2008, 01:33 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •