Java: How to make API call with data?

RajSharma :

I want to make API call similar to below curl command:

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer 
1djCb/mXV+KtryMxr6i1bXw" 
-d '{"operands":[]}' 
https://ads.line.me/api/v1.0/authority_delegations/get

What I am trying

public void send_deligation_request(String details[]) throws Exception{
    System.out.println(Arrays.toString(details));

    URL line_api_url = new URL("https://ads.line.me/api/v1.0/authority_delegations/get");
    String payload = "{operands:[]}";



    HttpURLConnection linec = (HttpURLConnection)line_api_url.openConnection();
    linec.setDoInput(true);
    linec.setDoOutput(true);
    linec.setRequestMethod("POST");
    linec.setRequestProperty("Content-Type", "application/json");
    linec.setRequestProperty("Authorization", "Bearer "+access_token);

    OutputStreamWriter writer = new OutputStreamWriter(linec.getOutputStream(), "UTF-8");
    writer.write(payload);


    BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                                    linec.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null) 
        System.out.println(inputLine);
    in.close();
}

But I am getting below error:

[[email protected], 5514]
java.io.IOException: Server returned HTTP response code: 400 for URL: https://ads.line.me/api/v1.0/authority_delegations/get
  at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1840)
  at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
  at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
  at AuthorityDelegation.send_deligation_request(AuthorityDelegation.java:66)
  at AuthorityDelegation.read_csv(AuthorityDelegation.java:36)
  at AuthorityDelegation.main(AuthorityDelegation.java:20)

Could somebody please help me?

JRG :

HTTP code 400 means a BAD REQUEST.

I can't access the endpoint you have shared but here is free online REST API which I am using for demonstrating ..

curl -X POST \
  https://jsonplaceholder.typicode.com/posts \
  -H 'cache-control: no-cache' \
  -H 'postman-token: 907bbf75-73f5-703f-c8b6-3e1cd674ebf7' \
  -d '{
        "userId": 100,
        "id": 100,
        "title": "main title",
        "body": "main body"
    }'
  • -H = headers
  • -d = data

Sample Run:

[/c]$ curl -X POST \
>   https://jsonplaceholder.typicode.com/posts \
>   -H 'cache-control: no-cache' \
>   -H 'postman-token: 907bbf75-73f5-703f-c8b6-3e1cd674ebf7' \
>   -d '{
>         "userId": 100,
>         "id": 100,
>         "title": "main title",
>         "body": "main body"
>     }'

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   258  100   150  100   108    147    106  0:00:01  0:00:01 --:--:--   192{
  "{\n        \"userId\": 100,\n        \"id\": 100,\n        \"title\": \"main title\",\n        \"body\": \"main body\"\n    }": "",
  "id": 101
}

Java Code for the same is as follows:

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("application/octet-stream");
RequestBody body = RequestBody.create(mediaType, "{\n        \"userId\": 100,\n        \"id\": 100,\n        \"title\": \"main title\",\n        \"body\": \"main body\"\n    }");
Request request = new Request.Builder()
  .url("https://jsonplaceholder.typicode.com/posts")
  .post(body)
  .addHeader("cache-control", "no-cache")
  .addHeader("postman-token", "e11ce033-931a-0419-4903-ab860261a91a")
  .build();

Response response = client.newCall(request).execute();

Another example of calling REST POST call with data ..

User user = new User();
user.setFirstName("john");
user.setLastName("Maclane");

ResteasyClient client = new ResteasyClientBuilder().build();
ResteasyWebTarget target = client.target("URL");
Response response = target.request().post(Entity.entity(user, <MEDIATYPE>));
//Read output in string format
System.out.println(response.getStatus());
response.close(); 

Here is the what your code looks like when I update it with my endpoints and payload.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

public class TestClass {

    public static final String POST_URL = "https://jsonplaceholder.typicode.com/posts";

    public static final String POST_DATA = "{\"userId\": 100,\"id\": 100,\"title\": \"main title\",\"body\": \"main body\"}";

    public static void main(String[] args) throws Exception {
        String[] details = {};
        System.out.println(Arrays.toString(details));

        URL line_api_url = new URL(POST_URL);
        String payload = POST_DATA;

        HttpURLConnection linec = (HttpURLConnection) line_api_url
                .openConnection();
        linec.setDoInput(true);
        linec.setDoOutput(true);
        linec.setRequestMethod("POST");
        linec.setRequestProperty("Content-Type", "application/json");
        linec.setRequestProperty("Authorization", "Bearer "
                + "1djCb/mXV+KtryMxr6i1bXw");

        OutputStreamWriter writer = new OutputStreamWriter(
                linec.getOutputStream(), "UTF-8");
        writer.write(payload);

        BufferedReader in = new BufferedReader(new InputStreamReader(
                linec.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

In nutshell, check the API documentation and ensure the request payload is of correct format as 400 means BAD REQUEST.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464434&siteId=1