【问题标题】:Error accessing a Web API which works well using POSTMAN访问使用 POSTMAN 运行良好的 Web API 时出错
【发布时间】:2017-12-04 00:52:04
【问题描述】:

我正在尝试调用 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);
    }
}
}

【问题讨论】:

  • 你的 web api 的参数是什么??
  • 您将 Content-Type 设置为“application/json”,然后将 UrlEncodedFormEntity 作为正文传递 - 这不是 JSON。尝试传递原始 JSON 以检查这是否适合您
  • @VitalyZ 谢谢,使用原始 JSON 代替 UrlEncodedFormEntity 作为正文。

标签: java api web apache-httpclient-4.x postman


【解决方案1】:

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

            JSONObject json = new JSONObject();
            json.put("requestType", "xxxx");
            json.put("projectToken", "xxxxxxxxxxxxxx");
            StringEntity params = new StringEntity(json.toString());
            post.setEntity(params); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-18
    • 2020-02-17
    • 1970-01-01
    • 2020-05-21
    • 2020-03-05
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多