1
我想调用一个WEB API并使用下面的代码获取JSON输出。错误访问使用POSTMAN运行良好的Web API
我用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);
}
}
}
什么是你的网络API的参数? – ELITE
您将Content-Type设置为“application/json”,然后将UrlEncodedFormEntity作为正文传递 - 这不是JSON。尝试通过原始JSON来检查这是否适用于您 – VitalyZ
@VitalyZ谢谢,使用原始JSON而不是UrlEncodedFormEntity身体的工作。 – wishman