繁体   English   中英

访问使用POSTMAN可以正常工作的Web API时出错

[英]Error accessing a Web API which works well using POSTMAN

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

我已经使用POSTMAN进行了测试,并且效果很好 标头中包含两个值,而POST请求的正文中包含多个值。

但是,当我尝试使用Apache HTTP Client访问相同的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);
    }
}
}

如@VitalyZ所述,我不应该将UrlEncodedFormEntity用作主体,而应使用原始JSON。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM