Rectangle 27 1

It seems you are POSTing incorrect JSON. The JSON generated by your code:

{
  "endTimeMillis": 1487772000000,
  "startTimeMillis": 1487721600000,
  "bucketByTime": {
    "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps",
    "dataTypeName": "com.google.step_count.delta"
  },
  "aggregateBy": [
    {
      "dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps",
      "dataTypeName": "com.google.step_count.delta"
    }
  ]
}
bucketByTime
"bucketByTime": { "durationMillis": 86400000 }

It seems that you are not adding the jobj3 variable in your code to the payload at all, which would contain the correct bucketByTime value.

OMG I didn't notice that silly mistake.Thank you very very much........

How to post a complex JSON object to cURL request in java - Stack Over...

java json curl http-post google-fit
Rectangle 27 1

I don't see it documented but curl -F @ apparently trying to be helpful fills in Content-type for some extensions/suffixes, including image/jpeg for .jpg. HttpClient does not, and defaults everything to the MIME 'I don't know' type application/octet-stream which presumably caused your error. Use the 3-arg ctor that sets the content-type

new ByteArrayBody (data, ContentType.create("image/jpeg"), null)

or if you want to specify the filename attribute, which curl -F @ also does but web servers (unlike browsers) usually don't care about, supply a String in place of the null third argument.

Java equivalent of curl post request with image and text - Stack Overf...

java curl http-post mime-types
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 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 9

Related posts and questions

curl -i -H "Content-Type: application/json" -X POST -d '{"id":100,"username":"JohnBlog","name":"John","lastName":"Blog","email":"JohnBlog@user.com"}' http://localhost:8080/[YOURWEBAPP]/api/user/add

Here I explore different errors you might come across after you have made a curl call and what might have possibly gone wrong.

HTTP/1.1 404 Not Found
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 949
Date: Tue, 04 Jun 2013 02:59:35 GMT

This implies that the REST API does not exist in the URL you have provide.

  • You might have a typo in your request (believe me this can happen)!
  • It could be that your spring configuration is not right. If this is the case it needs further digging into what has actually gone wrong but I have provided some initial actions you need to do before start your more sophisticated investigation.

After you have made sure that everything is done perfectly right and nothing is wrong with your Configuration nor you URL: - Run a maven clean. - Undeploy your web app or simply delete it. - Redeploy the web app - Make sure to use only one version of Spring in your maven/gradle

HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 968
Date: Tue, 04 Jun 2013 03:08:05 GMT
Connection: close

The only reason behind this is that fact that your request is not formatted correctly. If you checkout the detailed curl response you should be able to see "The request sent by the client was syntactically incorrect.".

Either your JSON format is not right or you are missing a mandatory parameter for the JAVA object.

Make sure you provide the JSON object in correct format and with the right number of parameters. Nullable properties are not mandatory but you do have to provide data for all NotNullable properties. It is VERY important to remember that Spring is using Java reflection to turn yours JSON file into Java objects, what does this mean? it means that variable and method names are CasE SensItiVe. If your JSON file is sending the variable "userName", than your matching variable in your Java object MUST also be named "userName". If you have getters and setters, they also have to follow the same rule. getUserName and setUserName to match our previous example.

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

The Json media type is not supported by your web service. This could be due to your annotation not specifying the media type or you not specifying the media type in Curl post command.

Check your message convertor is set up correctly and make sure the web service annotation matches the example above. If these were fine, make sure you specify the content-type in your Curl post request.

The json media type is not supported by your web service.

HTTP/1.1 200 OK 
Server: Apache-Coyote/1.1 
Content-Type: application/json;charset=UTF-8 
Transfer-Encoding: chunked 
Date: Tue, 04 Jun 2013 03:06:16 GMT

This FAQ was not possible if it wasn't for all the people who provided the following posts and questions (this list will expand if I come across useful related posts/questions):

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

java - Spring 4.x/3.x (Web MVC) REST API and JSON2 Post requests, how ...

java json spring curl html-post
Rectangle 27 9

Related posts and questions

curl -i -H "Content-Type: application/json" -X POST -d '{"id":100,"username":"JohnBlog","name":"John","lastName":"Blog","email":"JohnBlog@user.com"}' http://localhost:8080/[YOURWEBAPP]/api/user/add

Here I explore different errors you might come across after you have made a curl call and what might have possibly gone wrong.

HTTP/1.1 404 Not Found
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 949
Date: Tue, 04 Jun 2013 02:59:35 GMT

This implies that the REST API does not exist in the URL you have provide.

  • You might have a typo in your request (believe me this can happen)!
  • It could be that your spring configuration is not right. If this is the case it needs further digging into what has actually gone wrong but I have provided some initial actions you need to do before start your more sophisticated investigation.

After you have made sure that everything is done perfectly right and nothing is wrong with your Configuration nor you URL: - Run a maven clean. - Undeploy your web app or simply delete it. - Redeploy the web app - Make sure to use only one version of Spring in your maven/gradle

HTTP/1.1 400 Bad Request
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 968
Date: Tue, 04 Jun 2013 03:08:05 GMT
Connection: close

The only reason behind this is that fact that your request is not formatted correctly. If you checkout the detailed curl response you should be able to see "The request sent by the client was syntactically incorrect.".

Either your JSON format is not right or you are missing a mandatory parameter for the JAVA object.

Make sure you provide the JSON object in correct format and with the right number of parameters. Nullable properties are not mandatory but you do have to provide data for all NotNullable properties. It is VERY important to remember that Spring is using Java reflection to turn yours JSON file into Java objects, what does this mean? it means that variable and method names are CasE SensItiVe. If your JSON file is sending the variable "userName", than your matching variable in your Java object MUST also be named "userName". If you have getters and setters, they also have to follow the same rule. getUserName and setUserName to match our previous example.

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1051
Date: Wed, 24 Aug 2011 08:50:17 GMT

The Json media type is not supported by your web service. This could be due to your annotation not specifying the media type or you not specifying the media type in Curl post command.

Check your message convertor is set up correctly and make sure the web service annotation matches the example above. If these were fine, make sure you specify the content-type in your Curl post request.

The json media type is not supported by your web service.

HTTP/1.1 200 OK 
Server: Apache-Coyote/1.1 
Content-Type: application/json;charset=UTF-8 
Transfer-Encoding: chunked 
Date: Tue, 04 Jun 2013 03:06:16 GMT

This FAQ was not possible if it wasn't for all the people who provided the following posts and questions (this list will expand if I come across useful related posts/questions):

java - Spring 4.x/3.x (Web MVC) REST API and JSON2 Post requests, how ...

java json spring curl html-post
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 4

-d x=1&y=2 (notice the =, not :) is form data (application/x-www-form-urlencoded) sent it the body of the request, in which your resource method should look more like

@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String sumPost(@FormParam("x") int x,
                      @FormParam("y") int y) {

}

and the following request would work

curl -XPOST "http://localhost:8080/CurlServer/curl/curltutorial/sumPost" -d 'x=5&y=3'
"x=5&y=3"

You could even separate the key value pairs

curl -XPOST "http://localhost:8080/..." -d 'x=5' -d 'y=3'
Content-Type
application/x-www-form-urlencoded

@QueryParams are supposed to be part of the query string (part of the URL), not part of the body data. So your request should be more like

curl "http://localhost:8080/CurlServer/curl/curltutorial/sumPost?x=1&y=2"

With this though, since you are not sending any data in the body, you should probably just make the resource method a GET method.

@GET
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
public String sumPost(@QueryParam("x") int x,
                      @QueryParam("y") int y) {
}

If you wanted to send JSON, then your best bet is to make sure you have a JSON provider[1] that handle deserializing to a POJO. Then you can have something like

public class Operands {
    private int x;
    private int y;
    // getX setX getY setY
}
...
@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String sumPost(Operands ops) {

}

[1]- The important thing is that you do have a JSON provider. If you don't have one, you will get an exception with a message like "No MessageBodyReader found for mediatype application/json and type Operands". I would need to know what Jersey version and if you are using Maven or not, to able to determine how you should add JSON support. But for general information you can see

since you are not sending any data in the body, you should probably just make the resource method a GET method.

Maybe what I should've said is "since the resource method is not expecting any data in the body". You have no method parameters to accept a body. Generally a method argument to accept a body has no annotations. In most cases that is how it is known to be the entity body (the exception to the case being form data). In your case the data is expected to come in the URL (@QueryParam)

okay it is obvious that i made a mistake using queryparam, i didn't know that queryparam is for url. but if i change it to form param will that mean that the x and y are in the body of the http request ?

Yes. And with -d, that sends it in the body. Then the first example is what you would go with.

do I understand that -d '{"x":3, "y":4}' doesn't mean that the request is json? plus one for now

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

java - URL parameters are not being passed by curl POST - Stack Overfl...

java curl jersey http-post
Rectangle 27 4

-d x=1&y=2 (notice the =, not :) is form data (application/x-www-form-urlencoded) sent it the body of the request, in which your resource method should look more like

@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String sumPost(@FormParam("x") int x,
                      @FormParam("y") int y) {

}

and the following request would work

curl -XPOST "http://localhost:8080/CurlServer/curl/curltutorial/sumPost" -d 'x=5&y=3'
"x=5&y=3"

You could even separate the key value pairs

curl -XPOST "http://localhost:8080/..." -d 'x=5' -d 'y=3'
Content-Type
application/x-www-form-urlencoded

@QueryParams are supposed to be part of the query string (part of the URL), not part of the body data. So your request should be more like

curl "http://localhost:8080/CurlServer/curl/curltutorial/sumPost?x=1&y=2"

With this though, since you are not sending any data in the body, you should probably just make the resource method a GET method.

@GET
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
public String sumPost(@QueryParam("x") int x,
                      @QueryParam("y") int y) {
}

If you wanted to send JSON, then your best bet is to make sure you have a JSON provider[1] that handle deserializing to a POJO. Then you can have something like

public class Operands {
    private int x;
    private int y;
    // getX setX getY setY
}
...
@POST
@Path("/sumPost")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String sumPost(Operands ops) {

}

[1]- The important thing is that you do have a JSON provider. If you don't have one, you will get an exception with a message like "No MessageBodyReader found for mediatype application/json and type Operands". I would need to know what Jersey version and if you are using Maven or not, to able to determine how you should add JSON support. But for general information you can see

since you are not sending any data in the body, you should probably just make the resource method a GET method.

Maybe what I should've said is "since the resource method is not expecting any data in the body". You have no method parameters to accept a body. Generally a method argument to accept a body has no annotations. In most cases that is how it is known to be the entity body (the exception to the case being form data). In your case the data is expected to come in the URL (@QueryParam)

okay it is obvious that i made a mistake using queryparam, i didn't know that queryparam is for url. but if i change it to form param will that mean that the x and y are in the body of the http request ?

Yes. And with -d, that sends it in the body. Then the first example is what you would go with.

do I understand that -d '{"x":3, "y":4}' doesn't mean that the request is json? plus one for now

java - URL parameters are not being passed by curl POST - Stack Overfl...

java curl jersey http-post
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 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 8

You may want to use the OutputStreamWriter class.

final String toWriteOut = "{'value': 7.5}";
final OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(toWriteOut);
osw.close();

what would be the benefit over OutputStream?

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

java json post curl httpurlconnection
Rectangle 27 8

You may want to use the OutputStreamWriter class.

final String toWriteOut = "{'value': 7.5}";
final OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(toWriteOut);
osw.close();

what would be the benefit over OutputStream?

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

java json post curl httpurlconnection
Rectangle 27 2

In the POST before method, add PATH,try it.

Hello Credo, I assumed that you meant that I add a PATH annotation before my POST method. I tried that and now I get the HTTP/1.1 405 Method Not Allowed error...

java - Getting HTTP 404 Not Found when issuing POST using curl - Stack...

java json curl jersey http-post
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 8

AJAX is no different from any other HTTP call. You can basically POST the same URL from Java and it shouldn't matter as far as the target server is concerned:

final URL url = new URL("http://localhost:8080/SearchPerson.aspx/PersonSearch");
final URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConnection.connect();
final OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(("{\"fNamn\": \"" + stringData + "\"}").getBytes("UTF-8"));
outputStream.flush();
final InputStream inputStream = urlConnection.getInputStream();

The code above is more or less equivalent to your jQuery AJAX call. Of course you have to replace localhost:8080 with the actual server name.

If you need more comprehensive solution, consider httpclient library and jackson for JSON marshalling.

Thank you Tomasz for your reply. But still, I have a question! I would like to send the request to ratsit.se/BC/SearchPerson.aspx website. I have read their client part code and understood that they are sending in the following way: codepaste.net/u7qc1o Now I would like to write this ajax request in Java I did the things that you mentioned in the answer: codepaste.net/1rbgpx but still nothing,,, Can you help me please and let me know what is wrong ?

Ajax call in Java client application - Stack Overflow

java ajax xmlhttprequest