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 = "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);
}
}
}
As @VitalyZ mentioned, I shouldn't have used UrlEncodedFormEntity as body, instead used raw JSON.
JSONObject json = new JSONObject();
json.put("requestType", "xxxx");
json.put("projectToken", "xxxxxxxxxxxxxx");
StringEntity params = new StringEntity(json.toString());
post.setEntity(params);