it-swarm.com.de

Java: Wie mache ich einen API-Aufruf mit Daten?

Ich möchte einen API-Aufruf ähnlich dem folgenden curl-Befehl machen:

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

Was ich versuche

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

Aber ich bekomme einen Fehler:

[[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)

Könnte mir bitte jemand helfen?

7
RajSharma

HTTP-Code 400 bedeutet eine SCHLECHTE ANFRAGE.

Ich kann nicht auf den von Ihnen freigegebenen Endpunkt zugreifen, aber hier ist die kostenlose Online-API REST, die ich zur Demonstration verwende.

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 = Kopfzeilen 
  • -d = Daten

Probelauf:

[/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 für dasselbe ist wie folgt:

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

Ein weiteres Beispiel für den Aufruf von REST POST mit Daten. 

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

So sieht Ihr Code aus, wenn ich ihn mit meinen Endpunkten und meiner Nutzlast aktualisiere.

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

Kurz gesagt, überprüfen Sie die API-Dokumentation und stellen Sie sicher, dass die Anforderungsnutzlast das richtige Format hat, da 400 BAD REQUEST bedeutet.

13
JRG

Es handelt sich um einen Fehler von 400, was auf schlechte Anfrage hinweist. Bitte überprüfen Sie diesen Link unten. 

Wie ermittle ich den 400 HTTP-Fehler in Java?

2
SaAn

Vielen Dank an alle für Ihre Hilfe.

public JSONObject send_post() {
    HttpClient httpClient = HttpClientBuilder.create().build();
    JSONObject jsonObject = null;

    try {

        HttpPost request = new HttpPost(this.URL + this.object_type + this.request_type);
        StringEntity params = null;
        if (this.request_type.equals("/get")) {
            params = new StringEntity("{\"accountId\":\"5514\"}");
        } else if (this.request_type.equals("/set")) {
            // params = new
            // StringEntity("{\"accountId\":\"5514\",\"operands\":[{\"id\":40151,\"name\":\"ddddd\"}]}");
            String output = String.format("{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"name\":\"%s\"}]}",
                    this.params[0], this.params[1]);
            if (this.params[1].equals("OptimizationOff")) {
                output = String.format(
                        "{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"bidOptimizationType\":\"%s\"}]}",
                        this.params[0], "NONE");
            } else if (this.params[1].equals("OptimizationOn")) {
                output = String.format(
                        "{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"bidOptimizationType\":\"%s\",\"bidOptimizationGoal\":\"%s\"}]}",
                        this.params[0], this.params[2], this.params[3]);
            }
            if (object_type.equals("/ads")) {
                output = String.format("{\"accountId\":\"5514\",\"operands\":[{\"id\":%s,\"bidAmount\":\"%s\"}]}",
                        this.params[0], this.params[1]);
            }
            params = new StringEntity(output);
        }
        request.addHeader("content-type", "application/json");
        request.addHeader("Authorization", "Bearer " + this.Access_Token);
        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println("API Resonse :"+result.toString());
        jsonObject = new JSONObject(result.toString());

    } catch (Exception ex) {

        ex.printStackTrace();

    } finally {

    }
    return jsonObject;

}
1
RajSharma

OutputStreamWriter puffert die Ausgabe. Nach dieser Zeile in Ihrem Code:

writer.write(payload);

füge diese Zeile hinzu

writer.flush();

Ich würde erwarten, dass Ihr Problem behoben wird.

0
Mike

Dies hilft Ihnen jedoch möglicherweise nicht genau bei einem vorhandenen HTTP-Aufruf unter Verwendung der herkömmlichen HttpURLConnection. Ein interessanter Weg, um dies in letzter Zeit zu erreichen, besteht in der Verwendung von HTTP/2 Client und testen Sie das zuletzt eingeführte Inkubatormodul jdk.incubator.http aus Java 9. 

Ein einfacher Weg (Schnellstart) zum Verspotten eines POST - Aufrufs, der dasselbe verwendet, lautet wie folgt:

  1. Erstellen Sie ein Java-Modul in Ihrem Projekt und definieren Sie module-info.Java als:

    module http.trial { 
        requires jdk.incubator.httpclient;
    }
    
  2. Erstellen Sie im Modul ein Paket und eine Klasse mit dem Namen HttpPost mit folgendem Inhalt:

    import jdk.incubator.http.HttpRequest;
    import jdk.incubator.http.HttpClient;
    import jdk.incubator.http.HttpResponse;
    import Java.io.IOException;
    import Java.net.URI;
    import Java.net.URISyntaxException;
    
    public class HttpPost {
    
      public static void main(String[] args) {
    
        // Request builder
        URI uri = null;
        try {
            uri = new URI("https://ads.line.me/api/v1.0/authority_delegations/get");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        HttpRequest.BodyProcessor bodyProcessor = HttpRequest.BodyProcessor.fromString("{\"operands\":[]}");
        HttpRequest request = HttpRequest.newBuilder().uri(uri)
                        .header("Content-Type", "application/json")
                        .header("Authorization", "Bearer 1djCb/mXV+KtryMxr6i1bXw")
                        .POST(bodyProcessor)
                        .build();
    
        // Client
        HttpClient httpClient = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();
        System.out.println(httpClient.version());
    
        // Response builder
        HttpResponse response = null;
        try {
            response = httpClient.send(request, HttpResponse.BodyHandler.asString());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    
        System.out.println("StatusCode = " + response.statusCode());
        System.out.println("Response = " + response.body().toString());
      }
    }
    
0
nullpointer