1
WEB APIを呼び出し、次のコードを使用してJSON出力を取得しようとしています。POSTMANを使用してうまく動作するWeb APIにアクセスする際のエラー
私はこれをPOSTANを使用してとテストしました。これはうまく動作します。ヘッダーには2つの値があり、POST要求の場合は本体に2つの値があります。
しかし、私は私が得る同じWEB APIにアクセスするためにのApache HTTPクライアントを使用しようとしたとき、次の出力とエラー:
Response Code : 200
Result:{"errorCode":3000,"errorMessage":"Invalid request parameters"}
コード:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
public class WhiteSourceAPI {
public static void main(String[] args) {
try {
String url = "https://example.com/api";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
//header
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept-Charset", "UTF-8");
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("requestType", "xxxx"));
urlParameters.add(new BasicNameValuePair("projectToken", "xxxx-xxxx-xxxx-xxxx"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println("Result:" +result);
} catch (IOException ex) {
Logger.getLogger(WhiteSourceAPI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
ウェブAPIのパラメータは何ですか? – ELITE
Content-Typeを "application/json"に設定し、UrlEncodedFormEntityを本文として渡します。これはJSONではありません。これがうまくいくかどうかを確認するために未処理のJSONを渡してください。 – VitalyZ
@VitalyZありがとうございました。UrlEncodedFormEntityの代わりにraw JSONを使用しました。 – wishman