I have a rest post call. whenever I try to hit using postman it is working fine. but If I try same post call using JerseyAPI Client. I'm getting 400 Bad request
String URI = "rest uri";
Client client = Client.create();
WebResource webResource = client.resource(URI);
try {
String input1 = "{\"callType\": \"UPDATE\",\"emails\": [\"qa_tester2222#gmail.com\",\"qa_tester2222#gmail.com\"],\"event\": \"UPDATE_EVENT\",\"externalIds\": [ \"id\" ], \"fraudAction\": \"CONFIRMED_FRAUD\",\"fraudCategory\": \"Account Takeover\",\"memo\": \"test fraud case management for AD\",\"origin\": \"SE4\",\"phones\": [],\"requester\": \"corsairUser\",\"source\": \"LIVE\" }";
ClientResponse response = webResource.type("application/json")
.header("Authorization", "Basic secretKey")
.post(ClientResponse.class, input1);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (
Exception e) {
e.printStackTrace();
}
}
If I run same request in Postman using a above input, I'm able to hit api successfully and get 200, but getting 400 in JerseyAPI
Since you are getting a Bad Request response, I think you should create your JSON string using a proper JSON tool. You can start by creating a JSON object from your string and then use the JSON object to retrieve the input.
Creating the JSON object:
JSONObject jsonObject = new JSONObject(string);
Using the JSON object as your input:
ClientResponse response = webResource.type("application/json")
.header("Authorization", "Basic secretKey")
.post(ClientResponse.class, jsonObject.toString());
Related
I am trying to implement the MOT history API https://dvsa.github.io/mot-history-api-documentation/ and they give an example using CURL which works with the supplied api key successfully when using an online CURL tool.
I am trying to implement this in Android and realise I have to use something like HttpPost rather than CURL, this is my code:
//Tried with full URL and by adding the registration as a header.
//HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests?registration=" + reg_selected);
HttpPost httpPost = new HttpPost("https://beta.check-mot.service.gov.uk/trade/vehicles/mot-tests");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json+v6");
httpPost.addHeader("x-api-key", "abcdefgh123456");
httpPost.addHeader("registration", reg_selected);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = response.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String readLine = bufferedReader.readLine();
String jsonStr = readLine;
JSONObject myJsonObj = new JSONObject(jsonStr);
}else if (response.getStatusLine().getStatusCode() == 400){
//Bad Request Invalid data in the request. Check your URL and parameters
error_text = "Bad Request";
}else if (response.getStatusLine().getStatusCode() == 403){
//Unauthorised – The x-api-key is missing or invalid in the header
error_text = "Authentication error"; //<<<< FAILS HERE 403
}
response.getStatusLine().getStatusCode() returns • "403 – Unauthorised – The x-api-key is missing or invalid in the header".
However the x-api-key that I use works correctly with the online CURL test so the actual key is correct but how I am adding it to my android code request must be invalid or similar.
Can anyone throw any light as to the correct way to convert the CURL into Android java so that the server does not return 403?
Thanks
It's easy to do with Jsoup:
// CREATE CONNECTION
Connection conn=Jsoup.connect("URL_GOES_HERE");
// ADD POST/FORM DATA
conn.data("KEY", "VALUE");
// ADD HEADERS HERE
conn.header("KEY", "VALUE");
// SET METHOD AS POST
conn.method(Connection.Method.POST);
// ACCEPT RESPONDING CONTENT TYPE
conn.ignoreContentType(true);
try
{
// GET RESPONSE
String response = conn.execute().body();
// USE RESPONSE HERE
// CREATE JSON OBJECT OR ANYTHING...
} catch(HttpStatusException e)
{
int status = e.getStatusCode();
// HANDLE HTTP ERROR HERE
} catch (IOException e)
{
// HANDLE IO ERRORS HERE
}
Ps: I guess you are confused with Header and Post Data. The key etc (Credentials) must be used as Post Data and Content Type etc as Header.
I am trying to send request from Java to Twilio SMS API.
I am using java.net.http package:
var url = UriBuilder.fromUri(
"https://api.twilio.com/2010-04-01/Accounts/MyAccount/Messages.json").build();
var urlEncodedBody = URLEncoder.encode(String.format("To=%s&From=%s&Body=%s",
"+1123456789",
"+1223456789",
"Hello"),
StandardCharsets.UTF_8);
var request = HttpRequest.newBuilder(url)
.headers("Authorization", "Basic " + base64,
"Content-Type", "application/x-www-form-urlencoded")
.method("POST", HttpRequest.BodyPublishers.ofString(
urlEncodedBody))
.build();
HttpClient httpClient = HttpClient.newBuilder().build();
try {
var response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException |
InterruptedException e) {
throw new RuntimeException(e);
}
I keep getting the error response:
{"code": 21604, "message": "A 'To' phone number is required.", "more_info": "https://www.twilio.com/docs/errors/21604", "status": 400}
Any idea what I'm missing?
I think when you encode the body of the request you are also encoding the &s and =s so it just seems to be one string.
This answer on a different question suggests using a Map and encoding each value in turn. Using that as a basis, your could replace your string formatting with:
Map<String, String> parameters = new HashMap<>();
parameters.put("To", "+1123456789");
parameters.put("From", "+1223456789");
parameters.put("Body", "Hello");
String urlEncodedBody = parameters.entrySet()
.stream()
.map(e -> e.getKey() + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
I am trying to create a playlist using the Spotify API, and I am writing the POST request to the Spotify API endpoint in Java. I have also included every available scope from Spotify when I retrieve my access token. This is returning a response with an error message of:
{"error":{"message":"Error parsing JSON.","status":400}}
Here is what I have:
String http = "https://api.spotify.com/v1/users/" + userId + "/playlists";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(http);
JsonObject entityObj = new JsonObject();
JsonObject dataObj = new JsonObject();
dataObj.addProperty("name", "title");
dataObj.addProperty("public", "false");
entityObj.add("data", dataObj);
String dataStringify = GSON.toJson(entityObj);
StringEntity entity = new StringEntity(dataStringify);
post.setEntity(entity);
post.setHeader("Authorization", "Bearer " + accessToken);
post.setHeader("Content-Type", "application/json");
CloseableHttpResponse response = client.execute(post);
System.out
.println("Response Code : " + response.getStatusLine().getStatusCode());
String resp = EntityUtils.toString(response.getEntity());
JSONObject responseObj = new JSONObject(resp);
System.out.println(responseObj);
client.close();
Please let me know if you have any insights into what is wrong.
I am assuming you are using the org.json library as well as Google's Gson library. Using both doesn't make sense in this context. You won't need
String dataStringify = GSON.toJson(entityObj);
as entity Object already is a JSON Object. entityObj.toString() should be enough.
The current JSON Data you are sending looks like this:
{
"data":
{
"name":"title",
"public":"false"
}
}
Spotify ask for an JSON Object like this:
{
"name": "New Playlist",
"public": false
}
You only have to send the Data Object dataObj.
From my GAE server side code, Iam using urlfetchservice to update the datastore on another GAE. This results in Response code 302
Please find the code snippet below,
String urlVal = "https://valeo-is-qc-dev.appspot.com/a/qccards/"+modelObj.getQc_reference_id()+"/updatellcreference?llcref="+modelObj.getReference()+"&llcrefid="+modelObj.getId();
URL url = new URL(urlVal);
// Create HTTPRequest and set headers
com.google.appengine.api.urlfetch.FetchOptions fetchOptions = com.google.appengine.api.urlfetch.FetchOptions.Builder.withDefaults();
fetchOptions.doNotValidateCertificate();
fetchOptions.doNotFollowRedirects();
HTTPRequest httpRequest = null;
httpRequest = new HTTPRequest(new URL(url.toString()), HTTPMethod.PUT,fetchOptions);
httpRequest.addHeader(new HTTPHeader("Authorization", "OAuth " + token_id));
httpRequest.addHeader(new HTTPHeader("X-Appengine-Inbound-Appid", "valeo-is-llc-dev"));
httpRequest.addHeader(new HTTPHeader("Host", "https://test-is-abc-dev.appspot.com"));
httpRequest.addHeader(new HTTPHeader("Content-Type", "text/plain"));
URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
HTTPResponse httpResponse = null;
httpResponse = fetcher.fetch(httpRequest);
if (httpResponse.getResponseCode() == HttpURLConnection.HTTP_OK) {
LOGGER.log(Level.INFO, "abc def Bridge Response OK --- " + httpResponse.getResponseCode());
LOGGER.log(Level.INFO, "abc def Bridge Response OK --- " + httpResponse.toString());
} else {
// Server returned HTTP error code.
LOGGER.log(Level.INFO, "abc def Bridge Response FAIL --- " + httpResponse.getResponseCode());
}
I'm trying to post some json data using a http post method within my android application however i cannot seem to get it to work, the string is building fine and it works if i test using google chrome addon advanced rest client. I'm not the strongest with JSON hence why it is a string and not a JSON object. The Post request does not execute. Thanks in advance
String json = "{\"data\": [";
for (String tweet : tweetContent)
{
json = json + "{\"text\": \"" + tweet + "\", \"query\": \"" + SearchTerm + "\", \"topic\": \"movies\"},";
}
json = json.substring(0, json.length() - 1);
json = json + "]}";
Log.i("matt", json);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson?appid=matt-43#hotmail.com");
StringEntity entity = new StringEntity(json, HTTP.UTF_8);
httppost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.i(LOG_TAG, responseBody);
sentiments.add(responseBody.toString());
what is the response code that you are getting back after posting from the Http client.
It should be 200 for a successful Http post. Other wise there is some issue.
You are posting the JSON data to the URL. which application is reading this data from the URL. Is there some servlet on the other application that is reading JSON data fromrequest. check that and see.
Also check the request headers for the Http Post request. if you are setting all the request headers properly.