Rectangle 27 137

Your JSON is not correct. Instead of

JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString()); // <-- toString()
parent.put("auth", auth.toString());              // <-- toString()

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred);
parent.put("auth", auth);

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());

So, the JSONObject.toString() should be called only once for the outer object.

Another thing (most probably not your problem, but I'd like to mention it):

To be sure not to run into encoding problems, you should specify the encoding, if it is not UTF-8:

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

// ...

OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

POST request send json data java HttpUrlConnection - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 18

private JSONObject uploadToServer() throws IOException, JSONException {
            String query = "https://example.com";
            String json = "{\"key\":1}";

            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            in.close();
            conn.disconnect();

            return jsonObject;
    }

POST request send json data java HttpUrlConnection - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 137

Your JSON is not correct. Instead of

JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred.toString()); // <-- toString()
parent.put("auth", auth.toString());              // <-- toString()

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
JSONObject cred = new JSONObject();
JSONObject auth=new JSONObject();
JSONObject parent=new JSONObject();
cred.put("username","adm");
cred.put("password", "pwd");
auth.put("tenantName", "adm");
auth.put("passwordCredentials", cred);
parent.put("auth", auth);

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());

So, the JSONObject.toString() should be called only once for the outer object.

Another thing (most probably not your problem, but I'd like to mention it):

To be sure not to run into encoding problems, you should specify the encoding, if it is not UTF-8:

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

// ...

OutputStream os = con.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

POST request send json data java HttpUrlConnection - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 18

private JSONObject uploadToServer() throws IOException, JSONException {
            String query = "https://example.com";
            String json = "{\"key\":1}";

            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            in.close();
            conn.disconnect();

            return jsonObject;
    }

POST request send json data java HttpUrlConnection - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 12

You can use this code for connect and request using http and json

try {

        URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
                + "&key=AIzaSyAhONZJpMCBqCfQjFUj21cR2klf6JWbVSo"
                + "&access_token=" + access_token);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

     }

if you see an error add this but this is not a good job.

if (Build.VERSION.SDK_INT >= 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

POST request send json data java HttpUrlConnection - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 12

You can use this code for connect and request using http and json

try {

        URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
                + "&key=AIzaSyAhONZJpMCBqCfQjFUj21cR2klf6JWbVSo"
                + "&access_token=" + access_token);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

     }

if you see an error add this but this is not a good job.

if (Build.VERSION.SDK_INT >= 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

POST request send json data java HttpUrlConnection - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 2

but

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
byte[] outputBytes = rootJsonObject.getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);

POST request send json data java HttpUrlConnection - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 2

but

OutputStreamWriter wr= new OutputStreamWriter(con.getOutputStream());
wr.write(parent.toString());
byte[] outputBytes = rootJsonObject.getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);

POST request send json data java HttpUrlConnection - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 2

If the request is a XmlHttpRequest sent from Javascript, then the "application/json" content type will be understood and a download will not occur. This is be true for both GET and POST requests. If one is doing a file upload, Libraries such as JQuery, ExtJS etc create a hidden form with a setting of "application/x-www-form-urlencoded" and post it (all without the users interaction). This means the response is being interpreted by the browser, not Javascript. The only way around this is to set the content type of the returning JSON to "text/html" (NOT "text/plain" or else the browser tries to add tags).

"...create a hidden form with a setting of "application/x-www-form-urlencoded" and post it..." You can also create the Ajax call yourself, and make it "application/json". But it works whether it's json or x-www-form-urlencoded, at least for me. I did create the form with my own ajax coding though.

HttpUrlConnection Post causes the browser to download the response JSO...

java json servlets httpurlconnection alfresco
Rectangle 27 1

I have checked the API DOC for Jackson ObjectMapper class, for the method writeValue (here) There, it states that the method won't close the stream explicitly, unless you have set it at the JSonFactory, or when you close the Mapper.

Then, maybe you'll need to add an explicit flush() and a close() on the OutputStream:

OutputStream out=connection.getOutputStream();
try {
    jsonParser.writeValue(out,dto);
    out.flush();
//catch and handle the exceptions if needed
} finally {
    out.close();
}

Request was executed when I added a code to access the response (to check for the status code)... strange.

How to write JSON into API call using Java HttpURLConnection? - Stack ...

java json servlets httpurlconnection
Rectangle 27 2

I guess the problem is more in the client side or a misconception in your side. It's correct behaviour if the browser prompts to download the file when it has a content type of application/json, because the browser itself doesn't know how to handle it. The browser can only display everything which matches a content type of at least text/* or image/*.

Normally, JSON responses are to be handled internally by JavaScript, which can perfectly handle ajaxical responses with a content type of application/json. You can test it by changing it to text/plain or text/javascript, you'll see that the browser will display it (because it matches text/*). But for JSON the correct content type is indeed application/json. Just keep it as is and use the right tools to download/open the JSON ;)

Understood. If the request is a XMLHTTPREQUEST sent from Javascript, then the "application/json" content type will be understood and a download will not occur. This is be true for both GET and POST requests. If one is doing a file upload, Libraries such as JQuery, ExtJS etc create a hidden form with a setting of "application/x-www-form-urlencoded" and post it (all without the users interaction). This means the response is being interpreted by the browser, not Javascript. The only way around this is to set the content type to "text/html" (NOT "text/plain" or else the browser tries to add tags).

HttpUrlConnection Post causes the browser to download the response JSO...

java json servlets httpurlconnection alfresco
Rectangle 27 9

It's the same problem I was having: HttpUrlConnection returns FileNotFoundException if you try to read the getInputStream() from the connection. You should instead use getErrorStream() when the status code is higher than 400.

More than this, please be careful since it's not only 200 to be the success status code, even 201, 204, etc. are often used as success statuses.

Here is an example of how I went to manage it

... connection code code code ...

// Get the response code 
int statusCode = connection.getResponseCode();

InputStream is = null;

if (statusCode >= 200 && statusCode < 400) {
   // Create an InputStream in order to extract the response object
   is = connection.getInputStream();
}
else {
   is = connection.getErrorStream();
}

... callback/response to your handler....

In this way, you'll be able to get the needed response in both success and error cases. Hope this helps!

http - Read error response body in Java - Stack Overflow

java http httpurlconnection
Rectangle 27 93

You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

There is a sample of AuthMsg class:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}
{"code":1,"message":"Logged in"}

Can I ask you, where you close the connection c?

Originally I wrote this in java 7 manner with try-with-resources, but someone decided to keep java 6, so connection closing was ignored finally. But yes, connection must be closed. I'll edit this later, thanks.

@kbec I still do not see where you close the connection. Could you please add this to your answer?

disconnect()

java - Parse JSON from HttpURLConnection object - Stack Overflow

java html json parsing httpurlconnection
Rectangle 27 54

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

The method write(int) in the type DataOutputStream is not applicable for the arguments (String)

Instead of write(int); I used String str = jsonString.toString(); byte[] data=str.getBytes("UTF-8"); printout.write(data); printout.flush (); printout.close (); It is working.

It's an old answer, but it worked great for me to move away from the deprecated DefaultHttpClient. I also moved from the deprecated NameValuePair to a JSON Object. BTW,I had to change the "write" to "writeBytes".

I was getting the error explained above, wrong parameter types for printout.write(), so I used printout.writeUTF(URLEncoder.encode(params.toString(), "UTF-8"));

java - Sending a JSON HTTP POST request from Android - Stack Overflow

java android json wcf httpurlconnection
Rectangle 27 52

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

The method write(int) in the type DataOutputStream is not applicable for the arguments (String)

Instead of write(int); I used String str = jsonString.toString(); byte[] data=str.getBytes("UTF-8"); printout.write(data); printout.flush (); printout.close (); It is working.

It's an old answer, but it worked great for me to move away from the deprecated DefaultHttpClient. I also moved from the deprecated NameValuePair to a JSON Object. BTW,I had to change the "write" to "writeBytes".

I was getting the error explained above, wrong parameter types for printout.write(), so I used printout.writeUTF(URLEncoder.encode(params.toString(), "UTF-8"));

java - Sending a JSON HTTP POST request from Android - Stack Overflow

java android json wcf httpurlconnection
Rectangle 27 1

Your OutputStream cannot call any terminal command, because it's bound to your http connection only. To run terminal commands from the jvm, you can use Runtime.getRuntime().exec As an alternative you can use Apache Commons Exec, which I prefer.

StringBuffer output = new StringBuffer();
        Process p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader = 
                        new BufferedReader(new InputStreamReader(p.getInputStream()));

                    String line = "";           
        while ((line = reader.readLine())!= null) {
            output.append(line + "\n");
        }
        // your output that you can use to build your json response:
        output.toString();

I had thought of this though, but didn't know where to implement it.

Execute terminal command in java with httpurlconnection and get respon...

java json jsp curl httpurlconnection
Rectangle 27 30

OutputStream expects to work with bytes, and you're passing it characters. Try this:

HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();

byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);

os.close();

Is it not possible to send a complex json object in this manner? For instance ... "{"points":[{"point":{"latitude":40.8195085182092,"longitude":-73.75127574479318},"description":"test"},{"point":{"latitude":40.2195085182092,"longitude":-74.75127574479318},"description":"test2"}],"mode":"WALKING"}" ... is an object that I'm sending via this method and I get an HTTP Response Code of 500.

@CrowMagnumb You should post a separate question. 500 means that the server has an internal error trying to process your request.

java - cURL and HttpURLConnection - Post JSON Data - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 30

OutputStream expects to work with bytes, and you're passing it characters. Try this:

HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();

byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);

os.close();

Is it not possible to send a complex json object in this manner? For instance ... "{"points":[{"point":{"latitude":40.8195085182092,"longitude":-73.75127574479318},"description":"test"},{"point":{"latitude":40.2195085182092,"longitude":-74.75127574479318},"description":"test2"}],"mode":"WALKING"}" ... is an object that I'm sending via this method and I get an HTTP Response Code of 500.

@CrowMagnumb You should post a separate question. 500 means that the server has an internal error trying to process your request.

java - cURL and HttpURLConnection - Post JSON Data - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 90

I don't know if it's the only problem, but you've got a classic Java glitch in there: You're not counting on the fact that read() is always allowed to return fewer bytes than you ask for. Thus, your read could get less than 1024 bytes but your write always writes out exactly 1024 bytes possibly including bytes from the previous loop iteration.

while ( (len1 = in.read(buffer)) > 0 ) {
         f.write(buffer,0, len1);
 }

Perhaps the higher latency networking or smaller packet sizes of 3G on Android are exacerbating the effect?

What a stupid mistake... thanks! This is what happens when you don't read the tutorial properly :)

What about initializing the buffer? What about protecting against exception? What about releasing the resources? I think it is a good but not a complete answer. There are other more complete answers here.

I would like to point out that the > 0 test can prematurely end the reading. The Documentation says that -1 is returned at the end of the stream.

@Clint : true, but the documentation also says (as of java 5), that 0 cannot be returned unless the 'len' param is 0 (If no byte is available (...) -1 is returned; otherwise, at least one byte is read). In java 2, 0 can be returned.

java - Android download binary file problems - Stack Overflow

java android download httpurlconnection fileoutputstream
Rectangle 27 13

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

well i did that but i still get a bad request as a server response.Now let me ask if i did everything corect :When i set the otherparameter should i put param1 or the name of my parameters?also,my json object is the first parameter so first i write this one and after that i write the otherparameters is that right?

On server side the param sequence does not matter.It seems you are puting json in payload ... in this otherParametersUrServiceNeed = "param1=a&param2=b&param3=c"; put the name of parameters that you server need this is just example ..You should first identify the parameters that you server need in request the add these params and there values in String otherParametersUrService as my example demonstrates.

If it is not confidential you can tell me what addition params your server need ..so that i can put them in above example .

Well it's not,it is okay if i give you the method signature??:long InsertStudentAbsences(SRV_Students_Absence objStudentAbsences, string Company, string Lng, string MainPeriod, string UserID, string CourseDate);

java - Sending a JSON HTTP POST request from Android - Stack Overflow

java android json wcf httpurlconnection