I'm trying to call a WEB API and get a JSON output using the following code.
I have tested this using POSTMAN, and it works fine. There are two values in the header and some more in the body for the POST Request.
But when I tried using the Apache HTTP Client to access the same WEB API I get the following output and error:
Response Code : 200
Result:{"errorCode":3000,"errorMessage":"Invalid request parameters"}
Code:
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 = "http://ift.tt/2uqlh9E";
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", "getProjectLibraryLocations"));
urlParameters.add(new BasicNameValuePair("projectToken", "8d7670d9-a872-4799-bdaf-0be814f56003"));
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);
}
}
}
Aucun commentaire:
Enregistrer un commentaire