访问使用 POSTMAN 运行良好的 Web API 时出错

问题描述 投票:0回答:1

我正在尝试使用以下代码调用 WEB API 并获取 JSON 输出。

我已经使用 POSTMAN 对此进行了测试 ,它工作正常。 POST 请求的标头中有两个值,正文中有更多值。

但是当我尝试使用 Apache HTTP 客户端访问相同的 WEB API 时,我得到以下输出和错误:

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);
    }
}
}
java postman apache-httpclient-4.x
1个回答
0
投票

正如 @VitalyZ 提到的,我不应该使用 UrlEncodedFormEntity 作为正文,而是使用原始 JSON。

            JSONObject json = new JSONObject();
            json.put("requestType", "xxxx");
            json.put("projectToken", "xxxxxxxxxxxxxx");
            StringEntity params = new StringEntity(json.toString());
            post.setEntity(params); 
© www.soinside.com 2019 - 2024. All rights reserved.