HTTP Error Code 415 - JSON arrays in JAVA - java

I am trying to produce and send via JAVA a JSON file and when I am trying to add a nested object with an array in order to fit an application's protocol (which is not important to the question) the java program cannot send the file because of an HTTP error, code 415 (unsupported media type), which is strange because the produced JSON works when I copy it in the destined application (Google's DialogFlow). In other words, JSON is functional but JAVA (version 1.8) does not recognize it. Does anyone have any ideas why that happens?
When the part with the JSONArray in not included in the JSON file the request is sent without problem (see code below). I have tried changing the content-type from "application/json;charset=utf8" to "application/json;charset=utf-8" or "application/json" but nothing worked (this part in not included in the code because the changes that resulted in JSON not working were in the block below).
Part not working:
static JSONObject messageToJSON()
{
JSONObject requestJson = new JSONObject();
JSONObject meta= new JSONObject();
JSONObject payload= new JSONObject();
JSONArray arrayJson = new JSONArray();
String messageData="My Message";
try
{
requestJson.put("message", messageData);
requestJson.put("messageType", "html");
payload.put("title", "Thanks");
payload.put("message", "Thank you");
arrayJson.put(payload);
meta.put("contentType", "300");
meta.put("templateId", "6");
meta.put("contentType", "300");
meta.put("payload", arrayJson);
requestJson.put("metadata", meta);
System.out.println(requestJson.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
return requestJson;
}
The part working (without the extra layer in JSON, e.g. the payload JSON object and the arrayJson JSON array):
static JSONObject messageToJSON()
{
JSONObject requestJson = new JSONObject();
JSONObject meta= new JSONObject();
JSONObject payload= new JSONObject();
JSONArray arrayJson = new JSONArray();
String messageData="My Message";
try
{
requestJson.put("message", messageData);
requestJson.put("messageType", "html");
meta.put("contentType", "300");
meta.put("templateId", "6");
meta.put("contentType", "300");
requestJson.put("metadata", meta);
System.out.println(requestJson.toString());
}
catch (JSONException e)
{
e.printStackTrace();
}
return requestJson;
}

Ok, I found the problem. I should have transformed the arrayJson from JSONArray type to string.
In other words, instead of
meta.put("payload", arrayJson);
I should have
meta.put("payload", arrayJson.toString());
or make the arrayJson in a string format from the beginning.

Related

how to get a message from this Json

I listen to the socket and it comes Json, but I can’t parse it to get a message
[private-meeting-chat.98,
{"success":true,"data":
{"message":"Fuhvvhjv",
"chat_message_type_id":1},
"socket":null}]
here is the code i use
privateChannel.listen("MeetingChatMessage", args -> {
Log.i("Log", Arrays.toString(args));
runOnUiThread(() -> {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(args);
JSONObject jsonObject = jsonArray.getJSONObject(0);
JSONObject jsonDATA= jsonObject.getJSONObject("data");
String message = jsonDATA.getString("message");
Log.i("Log", message);
} catch (JSONException e) {
e.printStackTrace();
}
});
}
args comes to me, I can see it in the logs, but I can’t get information from it
From your comments, it seems that args is a list/array where the 2nd element is the response from the channel. So you need to access that element and convert to json.
JSONObject jsonObject = new JSONObject(args[1]);
JSONObject jsonDATA= jsonObject.getJSONObject("data");
String message = jsonDATA.getString("message");
Also, since it's not working, did you check what the error stacktrace is?

How to pass an array to POST API?

In my Android application, I need to send an array as body (payload information) to a POST url.
In body, there are two params:
1. "env" : "dev"
2. "dNumber" : tn("+1232323"); // here I need to send an array.
Edited question: I need to send phone as an array like ["123131","4545545"]
I pass the array as created a JSON array and convert to string and passed.
private String tn(String tn) {
String json = "";
try {
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, tn);
json = jsonArray.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
and full code is:
try {
URL url;
HttpURLConnection urlConnection;
url = new URL(makeCallUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", String.format("%s %s", "Basic", secretKey));
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.connect();
// Setup the body of the url
JSONObject json = new JSONObject();
json.put("env", "dev");
json.put("destNumbers", tn("+123123"));
// Write the body on the wire
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
writer.write(json.toString());
writer.flush();
writer.close();
} catch (IOException e) {
Log.d(TAG, "IOException:" + e.getMessage());
e.printStackTrace();
}
If I try this, I got 400, Bad request exception.
Please help me to pass an array to POST api
I solved my problem using JSONArray and pass the array.
// creating json array
JSONArray numberArray = new JSONArray();
numberArray.put(0, tn);
// send the array with payload
JSONObject json = new JSONObject();
json.put("env", "DEV");
json.put("destNumbers", numberArray);
Now I get array as following:
destNumbers = ["3434343","3434334]
Update your tn() method. Instead of returning String it should return JSONArray.
private JSONArray tn(String tn) {
JSONArray jsonArray = new JSONArray();
try {
jsonArray.put(0, tn);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonArray ;
}
Although if still the 400 Bad request error occur than confirm and verify the request payload with your json.

How to add json to GET request query parameter?

I want json to be sent to GET request in query parameter to get the response for that json request.
If I use a link something like this :
www.url.com/search?query1=abc&filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
Then the url part appears blue if I do it as sysout statement, something like this:
www.url.com/search?query1=abc&filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
and the json appears as if it is not the part of the request.
To create a URL, I'm appending the manipulated JSON string to the URL and then sending the request. But it appears as two different strings.
Also I have used encoder to encode the JSON part
filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
In that case the brackets and double quotes everything in that json is encoded, even the equalTo sign. Also the link appears blue but while sending request it throws exception of 400 Bad Request, since the equalTo is also converted to its encoding format.
I tried encoding only the JSON part leaving the filter= in the url itself, something like this :
www.url.com/search?query1=abc&filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
The results that appear after the request is send is different from the results I want.
I'm using following code to create a JSON:
private String getVinFromInventoryRequest(String vin) throws JSONException {
JSONObject request = new JSONObject();
JSONArray orArray = new JSONArray();
for(String vin : vins) {
JSONObject termsObject = new JSONObject();
JSONObject vinsObject = new JSONObject();
JSONArray vinsArray = new JSONArray();
vinsArray.put(vin);
vinsObject.put("vin", vinsArray);
termsObject.put("terms", vinsObject);
orArray.put(termsObject);
}
request.put("or", orArray);
System.out.println("OfferMapper.getVinFromInventoryRequest " + request.toString());
return request.toString();
}
Also look what I found with a little googling :
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
For more info see : HTTP POST using JSON in Java

Creating JSON in android

Please have a look at the following. They are JSON formats. Don't worry about the username and id. THhey are fake. You can see the link here
Authenticate
POST /andromeda/prediction?username=alfred;api_key=79138a622755a2383660347f895444b1eb927730; HTTP/1.1
Host: bigml.io
Content-Type: application/json
Creating Prediction
curl https://bigml.io/andromeda/prediction?$BIGML_AUTH \
-X POST \
-H 'content-type: application/json' \
-d '{"model": "model/50a2eac63c19200bd1000008", "input_data": {"000001": 3}}'
Above, BIGML_AUTH means a variable which includes the user name and the API key.
Now, I am going to do these JSON calls with android. Below is my code
private JSONObject putJson()
{
HttpClient httpclient = new DefaultHttpClient();
JSONObject finalResult = null;
HttpPost httppost = new HttpPost("https://bigml.io/andromeda/prediction?username=alfred;api_key=79138a622755a2383660347f895444b1eb927730");
httppost.setHeader("Content-type", "application/json; charset=utf-8");
JSONObject json = new JSONObject();
try {
// Add your data
json.put("model","model/50a2eac63c19200bd1000008");
json.put("input_data", "{000001:3}");
StringEntity se = new StringEntity( json.toString());
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String jsonString = reader.readLine();
JSONTokener tokener = new JSONTokener(jsonString);
finalResult = new JSONObject(tokener);
}
catch(Exception e)
{
Log.d("Error here", "Error is here",e);
}
return finalResult;
}
I need to know whether I have coded the given Json in Android correctly. I can't run and check because when run and checked, it returns ID DOES NOT EXIST error.
Please let me know whether I have coded the JSON correctly, because I have not use JSON before.
There is a slight difference between your code and curl:
Your code:
// Add your data
json.put("model","model/50a2eac63c19200bd1000008");
json.put("input_data", "{000001:3}");
If you want to produce equivalent JSON as in your curl command, it should read:
// Add your data
json.put("model","model/50a2eac63c19200bd1000008");
JSONObject input_data = new JSONObject();
input_data.put("000001", 3);
json.put("input_data", input_data);
I encountered another thing which could cause problems. You read only the first line of your response. In many cases this is not a problem, because most JSON Objects are in single line. But if somebody enables DEBUG-mode on the API-server it can happen that the JSON object comes in multiple lines (aka. human readable).
BTW Google doesn't encourage developers to use DefaultHttpClient for Android versions > FROYO (makes ~ 97% of phones). For GINGERBREAD and newer we should use HttpUrlConnection for requesting web resources and REST/JSON.
I've made a small library called DavidWebb which makes live easier when making HTTP requests. With this library your code would look like this:
private JSONObject putJson() throws Exception {
JSONObject result = null;
try {
JSONObject json = new JSONObject();
// Add your data
json.put("model", "model/50a2eac63c19200bd1000008");
JSONObject input_data = new JSONObject();
input_data.put("000001", 3);
json.put("input_data", input_data);
Webb webb = Webb.create();
result = webb
.post("https://bigml.io/andromeda/prediction?username=alfred;api_key=79138a622755a2383660347f895444b1eb927730")
.body(json)
.ensureSuccess()
.asJsonObject()
.getBody();
} catch (JSONException e) {
// should not happen
// Log.d("Error here", "Error is here",e);
} catch (WebbException e) {
// carries the real exception
}
return result;
}
The link I've provided gives many alternatives for HTTP-request libraries for Android - you don't have to use DavidWebb.
org.json.JSONObject?
If so, then here your json code is fine & will give valid json too!
{
"model": "model/50a2eac63c19200bd1000008",
"input_data": "{000001:3}"
}

How to read resulting JSON data into Java ?

I am trying to read results of a JSON request into java, yet
The partial output of my JSON request looks like this :
"route_summary": {
"total_distance": 740,
"total_time": 86,
"start_point": "Marienstraße",
"end_point": "Feldbergstraße"
}
I would like to use the standard json library to extract the values in total_distance.
However I only seem to be able to get the 'route_summary' by doing this :
JSONObject json = null;
json = readJsonFromUrl(request);
json.get("route_summary");
Where
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
What I want is get 'into' route_summary, any clue / tip would be great !
You need to get route_summary, as you already did, and from that object you need to get the total_distance. This will give you back the route_summary.total_distance.
Code sample:
JSONObject object = new JSONObject(s);
int totalDistance = object.getJSONObject("route_summary").getInt("total_distance");
I would recommend you to use GSON library. You can create class which will represent the message and then automatically map JSON to object by invoking function: gson.fromJson(message, YourMessageClass.class).getRoute_summary().
Here is the example of such approach: https://sites.google.com/site/gson/gson-user-guide/#TOC-Object-Examples

Categories