web-dev-qa-db-ja.com

Java:データでAPI呼び出しを行う方法?

以下のcurlコマンドに似たAPI呼び出しを実行したい:

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

私が試みていること

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

しかし、私は以下のエラーを得ています:

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

誰かが私を助けてくれませんか?

6
RajSharma

HTTPコード400はBAD REQUESTを意味します。

共有しているエンドポイントにアクセスできませんが、こちらは無料のオンラインREST私がデモに使用しているAPIです。

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 =ヘッダー
  • -d =データ

サンプル実行:

[/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コードは次のとおりです。

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

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

エンドポイントとペイロードでコードを更新すると、コードは次のようになります。

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

簡単に言えば、APIドキュメントを確認し、リクエストペイロードの形式が正しいことを確認してください。400はBAD REQUESTを意味します。

13
JRG

これは400エラーです。つまり、不正なリクエストです。以下のリンクをご確認ください。

Javaの400 Httpエラーの詳細を見つける方法は?

2
SaAn

皆さんの助けに感謝します。以下のコードを使用して機能させました。

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は出力をバッファリングします。コードのこの行の後:

writer.write(payload);

この行を追加

writer.flush();

私はあなたの問題を修正することを期待しています。

0
Mike

ただし、これは、従来のHttpURLConnectionを使用した既存のHTTP呼び出しでは正確には役に立たない場合があります。しかし、最近これを実現する興味深い方法は、 HTTP/2クライアント を使用して、最新のインキュベータモジュールjdk.incubator.httpform Java 9。

同じことを使用してPOST呼び出しをモックする 簡単な方法 (クイックスタート)は次のとおりです。

  1. プロジェクト内に Java-module を作成し、module-info.Javaを次のように定義します。

    module http.trial { 
        requires jdk.incubator.httpclient;
    }
    
  2. モジュール内に、次の内容のパッケージとHttpPostという名前のクラスを作成します。

    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
Naman

Splunk APIからデータを取得し、認証/ SSLエラーを圧縮するScalaコード:

import Java.nio.charset.StandardCharsets
import Java.security.cert.X509Certificate
import Java.util.{ArrayList, List}

import javax.net.ssl.SSLContext
import org.Apache.commons.codec.binary.Base64
import org.Apache.http.NameValuePair
import org.Apache.http.client.HttpClient
import org.Apache.http.client.methods.HttpPost
import org.Apache.http.conn.ssl.{NoopHostnameVerifier, TrustSelfSignedStrategy}
import org.Apache.http.impl.client.HttpClients
import org.Apache.http.message.BasicNameValuePair
import org.Apache.http.ssl.SSLContextBuilder

class test {


  val sslContext: SSLContext = new SSLContextBuilder()
    .loadTrustMaterial(null, new TrustSelfSignedStrategy() {
      override def isTrusted(chain: Array[X509Certificate],
                             authType: String): Boolean = true
    })
    .build()

  val httpclient: HttpClient = HttpClients
    .custom()
    .setSSLContext(sslContext)
    .setSSLHostnameVerifier(new NoopHostnameVerifier())
    .build()
  val httpPost: HttpPost = new HttpPost(
    "https://splunk-api:8089/servicesNS/nobody/search/search/jobs/export")

  val params: List[NameValuePair] = new ArrayList[NameValuePair]()
  val searchString: String =
    "search index=prod_applogs OR index=prod_applogs source=\"*subscriber-daemon-*\" Data  Mutation | lookup data_clients.csv client OUTPUTNEW pow AS pow | stats count as numEvents, min(_time) as minTime by pow, Name | eval cost=round(exact(numEvents*0.000003),2)|eval date=strftime(minTime, \"%Y-%m-%d\")|fields *"
  params.add(new BasicNameValuePair("search", searchString))
  params.add(new BasicNameValuePair("output_mode", "csv"))
  params.add(new BasicNameValuePair("earliest_time", "1h"))
  params.add(new BasicNameValuePair("latest_time", "now"))


  val username: String = "userName"
  val password: String = "pwd"
  val auth: String = username + ":" + password

  val encodedAuth: Array[Byte] =
    Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1))
  val authHeaderVal: String = "Basic " + new String(encodedAuth)

}
0
Rajiv Singh