Getting a 400 after setting json parameters - java

I am trying to send the following json to a REST server from JAVA
{
"image_url":"image",
"job_fqn":"jobfqn",
"ignore_volumes":true
}
I am setting it as follows in my HttpClient
JSONObject json = new JSONObject();
json.put("image_url","image");
json.put("job_fqn","jobfqn");
json.put("ignore_volumes", "true");
StringEntity params = new StringEntity(json.toString());
post.setEntity(params);
HttpResponse response = client.execute(post);
This gives me a 400, after I remove
json.put("ignore_volumes", "true");
this is a valid input , not sure whats going on. The json from curl works fine, only fails in java

Have you tried json.put("ignore_volumes", true);?
Placing the Boolean true instead of the String true.

Try using true as a boolean and not as a string.
json.put("ignore_volumes", true);

Related

How to write / convert CURL for Android java

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.

Rest call with special characters giving "Event request must have valid JSON body" error in java

I'm trying to make a rest call from java. In request body, I have one field which contains special characters. If I execute this post request from java then its giving me "Event request must have valid JSON body" but when I execute same request from postman then I'm getting 200ok response.
Here is the request
{
"header": {
"headerVersion": 1,
"eventName": "add-incident",
"ownerId": "owner",
"appName": "abc",
"processNetworkId": "networkId",
"dataspace": "default"
},
"payload": {
"description": "Arvizturo tukorfurogepa€TM€¢ SchA1⁄4tzenstrasse a€¢",
"summary": "adding one issue"
}
}
This is how I'm executing request in java
String reqBody = "This is a json String cotaining same payload as above mentioned^^";
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()
).build();
HttpPost postRequest = new HttpPost("Adding URL here");
StringEntity input = new StringEntity(reqBody);
input.setContentType("application/json);
postRequest.setEntity(input);
postRequest.addHeader("Authorization","Bearer " + "Putting Authorisation Token Here");
HttpResponse response = httpClient.execute(postRequest);
Does anyone know what changes i need to do in code to resolve this issue?
Let me know if you want other information.
Thanks in advance.
To resolve this I just made the below change
String finalBody = new String(reqBody.getBytes("UTF-8"),"UTF-8");
I set the encoding of the HTTP request string to UTF-8. This resolved my issue.
String reqBody = "This is a json String cotaining HTTP request payload";
String finalBody = new String(reqBody.getBytes("UTF-8"),"UTF-8");
HttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build()
).build();
HttpPost postRequest = new HttpPost("Adding URL here");
StringEntity input = new StringEntity(finalBody, ContentType.APPLICATION_JSON);
postRequest.setEntity(input);
postRequest.addHeader("Authorization","Bearer " + "Putting Authorisation Token Here");
HttpResponse response = httpClient.execute(postRequest);
This looks like issue with Character encoding. You are setting setContentType to application/json but not setting character encoding which eventually defaulted to platform encoding type.
To ensure you are setting UTF-8 to handle such special characters , change your StringEntity initialization with below:
StringEntity input = new StringEntity(reqBody,ContentType.APPLICATION_JSON);
Also, remove input.setContentType("application/json"); call, as you don't need it once you use above mentioned constructor. This constructor will take care of using application/json as well as setting encoding as UTF-8

UTF-8 Encoding issue with HTTP Post object on AWS Elastic Beanstalk

I setting up a new server in AWS EBS with linux and configured the server to be UTF-8 because I use some text in Hebrew.
The code works on Windows but when I migrated to Linux this stopped working.
The code send HTTP post to another server and get JSON object from it and start to parse, All the Hebrew text is something like this: קבוצ×
I tried to add to AWS software configuration : JAVA_TOOL_OPTIONS -Dfile.encoding=UTF8
I tried to add JAVA_OPTIONS="-Dfile.encoding=UTF-8" to tomcat8.conf file. (aslo tried with JAVA_OPTS).
I tried to add catalina options also with encoding.
HttpPost request = new HttpPost(URL);
// Create JSON and set the API Token
JSONObject SendJson = new JSONObject();
SendJson.put(field, key);
StringEntity params =new StringEntity(SendJson.toString());
request.setEntity(params);
// set Header Type
request.addHeader("content-type", "application/json;charset=UTF-8");
request.addHeader("Accept-Encoding", "UTF-8");
// Execute and wait for response
HttpResponse httpResponse = httpClient.execute(request);
HttpEntity resEntity = httpResponse.getEntity();
// cast InputStream to String for JSON conversion
BufferedReader reader = new BufferedReader(new InputStreamReader( resEntity.getContent()));
//String strInputStream = EntityUtils.toString(resEntity,"UTF-8");
String strInputStream = reader.readLine();
//debug
System.out.println("David Encoding problem");
System.out.println(Charset.defaultCharset().name());
System.out.println(strInputStream);
JSONObject answerObj = new JSONObject(strInputStream);
Charset.defaultCharset().name() - output UTF-8
I get JSON with no Hebrew text :/
part of the JSON for example:
{"item_group_id":1,"item_group_name":"קבוצה ×","picture_link":""},
Thanks,
David
I fixed it.
I changed the locale to he_IL and he_IL.UTF8, then restarted the server and it worked.
Thanks!

Posting JSON object to HTTP server

So I'm developing an Android app (Java) that posts a JSON object to a web server. I've achieved this, but I'm battling to get the string value to display properly.
Instead of the server receiving "6666666666666", it receives "Ljava.lang.String;#41108be0]". How on earth do I go about fixing this? Here's my code:
protected Boolean doInBackground(String... ID) {
HttpClient httpClient = new DefaultHttpClient();
Date dateTime = new Date();
string deviceID=null;
try {
HttpPost request = new HttpPost("http://192.168.1.89:80/");
JSONObject json = new JSONObject();
json.put("IDNo", ID.toString());
json.put("DTSent", dateTime);
json.put("DeviceID", deviceID);
StringEntity se = new StringEntity(json.toString(), "UTF-8");
se.setContentType("application/json; charset=UTF-8");
request.setEntity(se);
request.setHeader( "Content-Type", "application/json");
}
Please help.
ID is a String-Array not just a string. the ... makes it an array. so either use ID[0] or remove the ... from the function declaration
You are passing in an array of strings (see the three dots?). Try using ID[0] instead.
Here is a useful post:

Get HTTP code from org.apache.http.HttpResponse

I'm using the org.apache.http.HttpResponse class in my Java application, and I need to be able to get the HTTP status code. If I used .toString() on it, I can see the HTTP status code in there. Is there any other function that I can just get the HTTP status code as either an int or String?
Thanks a bunch!
Use HttpResponse.getStatusLine(), which returns a StatusLine object containing the status code, protocol version and "reason".
I have used httpResponse.getStatusLine().getStatusCode() and have found this to reliably return the integer http status code.
httpResponse.getStatusLine().getStatusCode()
A example will be as below,
final String enhancementPayload ="sunil kumar";
HttpPost submitFormReq = new HttpPost("https://bgl-ast/rest/service/form/form-data");
StringEntity enhancementJson = new StringEntity(enhancementPayload);
submitFormReq.setEntity(enhancementJson);
submitFormReq.setHeader("Content-Type", "application/xml");
HttpResponse response = httpClient.execute( submitFormReq );
String result = EntityUtils.toString(response.getEntity());
System.out.println("result "+result);
assertEquals(200, response.getStatusLine().getStatusCode());

Categories

Resources