How to pass an array to POST API? - java

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.

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?

HTTP Error Code 415 - JSON arrays in 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.

Conversion error from String to JSONObject in Android [duplicate]

I have a JSON file with 2 JSON-Arrays in it:
One Array for routes and one Array for sights.
A route should consist of several sights where the user gets navigated to.
Unfortunately I am getting the error:
JSONException: Value of type java.lang.String cannot be converted to JSONObject
Here are my variables and the code that parses the JSON-File:
private InputStream is = null;
private String json = "";
private JSONObject jObj = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
// hier habe ich das JSON-File als String
json = sb.toString();
Log.i("JSON Parser", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Log.i("JSON Parser", json);
shows me that at the beginning of the generated string there is a strange sign:
but the error happens here:
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
04-22 14:01:05.043: E/JSON Parser(5868): Error parsing data
org.json.JSONException: Value //STRANGE SIGN HERE // of type
java.lang.String cannot be converted to JSONObject
anybody has a clue on how to get rid of these signs in order to create the JSONObject?
Reason is some un-wanted characters was added when you compose the String.
The temp solution is
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
But try to remove hidden characters on source String.
see this
http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
you try to use some thing like:
new JSONObject("{your string}")
Had the same problem for few days. Found a solution at last. The PHP server returned some unseen characters which you could not see in the LOG or in System.out.
So the solution was that i tried to substring my json String one by one and when i came to substring(3) the error went away.
BTW. i used UTF-8 encoding on both sides.
PHP side: header('Content-type=application/json; charset=utf-8');
JAVA side: BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
So try the solution one by one 1,2,3,4...! Hope it helps you guys!
try {
jObj = new JSONObject(json.substring(3));
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
This worked for me
json = json.replace("\\\"","'");
JSONObject jo = new JSONObject(json.substring(1,json.length()-1));
Here is UTF-8 version, with several exception handling:
static InputStream is = null;
static JSONObject jObj = null;
static String json = null;
static HttpResponse httpResponse = null;
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
HttpProtocolParams.setUseExpectContinue(params, true);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(params);
HttpGet httpPost = new HttpGet( url);
httpResponse = httpClient.execute( httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException ee) {
Log.i("UnsupportedEncodingException...", is.toString());
} catch (ClientProtocolException e) {
Log.i("ClientProtocolException...", is.toString());
} catch (IOException e) {
Log.i("IOException...", is.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8); //old charset iso-8859-1
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
reader.close();
json = sb.toString();
Log.i("StringBuilder...", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
try {
jObj = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
} catch (Exception e0) {
Log.e("JSON Parser0", "Error parsing data [" + e0.getMessage()+"] "+json);
Log.e("JSON Parser0", "Error parsing data " + e0.toString());
try {
jObj = new JSONObject(json.substring(1));
} catch (Exception e1) {
Log.e("JSON Parser1", "Error parsing data [" + e1.getMessage()+"] "+json);
Log.e("JSON Parser1", "Error parsing data " + e1.toString());
try {
jObj = new JSONObject(json.substring(2));
} catch (Exception e2) {
Log.e("JSON Parser2", "Error parsing data [" + e2.getMessage()+"] "+json);
Log.e("JSON Parser2", "Error parsing data " + e2.toString());
try {
jObj = new JSONObject(json.substring(3));
} catch (Exception e3) {
Log.e("JSON Parser3", "Error parsing data [" + e3.getMessage()+"] "+json);
Log.e("JSON Parser3", "Error parsing data " + e3.toString());
}
}
}
}
}
// return JSON String
return jObj;
}
This is simple way (thanks Gson)
JsonParser parser = new JsonParser();
String retVal = parser.parse(param).getAsString();
https://gist.github.com/MustafaFerhan/25906d2be6ca109f61ce#file-evaluatejavascript-string-problem
I think the problem may be in the charset that you are trying to use. It is probably best to use UTF-8 instead of iso-8859-1.
Also open whatever file is being used for your InputStream and make sure no special characters were accidentally inserted. Sometimes you have to specifically tell your editor to display hidden / special characters.
return response;
After that get the response we need to parse this By:
JSONObject myObj=new JSONObject(response);
On response there is no need for double quotes.
I made this change and now it works for me.
//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8);
The 3 characters at the beginning of your json string correspond to Byte Order Mask (BOM), which is a sequence of Bytes to identify the file as UTF8 file.
Be sure that the file which sends the json is encoded with utf8 (no bom) encoding.
(I had the same issue, with TextWrangler editor. Use save as - utf8 (no bom) to force the right encoding.)
Hope it helps.
In my case the problem occured from php file.
It gave unwanted characters.That is why a json parsing problem occured.
Then I paste my php code in Notepad++ and select Encode in utf-8 without BOM
from Encoding tab and running this code-
My problem gone away.
In my case, my Android app uses Volley to make a POST call with an empty body to an API application hosted on Microsoft Azure.
The error was:
JSONException: Value <p>iisnode of type java.lang.String cannot be converted to JSONObject
This is a snippet on how I was constructing the Volley JSON request:
final JSONObject emptyJsonObject = new JSONObject();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, emptyJsonObject, listener, errorListener);
I solved my problem by creating the JSONObject with an empty JSON object as follows:
final JSONObject emptyJsonObject = new JSONObject("{}");
My solution is along the lines to this older answer.
if value of the Key is coming as String and you want to convert it to JSONObject,
First take your key.value into a String variable like
String data = yourResponse.yourKey;
then convert into JSONArray
JSONObject myObj=new JSONObject(data);
For me, I just needed to use getString() vs. getJSONObject() (the latter threw that error):
JSONObject jsonObject = new JSONObject(jsonString);
String valueIWanted = jsonObject.getString("access_token"))

JSON response cutting off part way through

When downloading a JSON array, it cuts off 1/4 of the way through the string, its pretty huge - but it should get the entire string.
There are no errors thrown in the LogCat. This is the method I am using, I have been through it a few times and cant see a reason why it is cutting off. I am pretty new to this however.
public static JSONArray getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONArray jArray = null;
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON object
try {
Log.d("log_tag", "jresult: " + result + "finish");
jArray = new JSONArray(result);
//Log.e("log_tag", "result: " + jArray.toString());
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
I think once this is cracked I will be set. I will make this a class to use in future projects too so I dont have to keep rebuilding it!
EDIT: For loop where markers should be added to map:
try{
for(int i=0;i<arrayResultFromURL.length();i++){
JSONObject json_data = arrayResultFromURL.getJSONObject(i);
// assign attributes from the JSON string to local variables
String id =json_data.getString("id");
String title =json_data.getString("title");
String strap =json_data.getString("strap");
Double lat = (double) json_data.getDouble("lat");
Double lon = (double) json_data.getDouble("long");
theMap.addMarker(new MarkerOptions()
.position(new LatLng(lat, lon))
.title(title)
.snippet(strap));
}
}catch (Exception e){
Log.e("log_tag", "error in array: " + e.toString());
}
Maybe your problem comes from the way your are treating the response object. Check this thread.
If not try to check the size of the response first to see if you are receving all.
httpResponse.getEntity().getContentLength()
Also just in case you didn't know there is a nice library (i've been using it since i found it) that simplifies json parsing ckeck it out here.
These type of things can best be done by libraries such as GSON or Jackson
Also, if your goal is to create a JSONArray, there is a constructor that takes in a JSONTokener. JSONTokener can in turn be constructed from your InputStream.

Error converting a HTTP POST response to JSON

When I try to convert an HTTP POST response to JSONArray I get the error:
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONArray
the error happens in the line: JSONArray jArray = new JSONArray(result);
the value of the string result is [{"return":"1"}] but it includes an extra blank character at the beginning that when removed, solves the problem. However, this character is not blank because a trim does not solve the problem. I believe there is some problem with the POST response, maybe badly constructed? (or maybe the POST request is wrong?) Any help is welcome.
A GET request works just fine, but I need to do a POST request.
This is the code:
HttpPost("usuarioLogin.php",nameValuePairs);
String result = ConvertResponseToString();
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ret = json_data.getInt("return");
retorno = (ret==1)?true:false;
}
}
catch(JSONException e1){
e1.printStackTrace();
} catch (ParseException e1) {
e1.printStackTrace();
}
this is the code of the function HttpPost()
private void HttpPost(String php, ArrayList<NameValuePair> nameValuePairs)
{
try{
HttpClient httpclient = new DefaultHttpClient();
String host = com.android.taggies.LoginUser.getContext().getResources().getString(R.string.host);
HttpPost httppost = new HttpPost("http://"+host+php);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
this is the code of the function ConvertResponseToString()
private String ConvertResponseToString()
{
//convert response to string
String result = null;
try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
return result;
}
this is the code of my php that replies to the POST
<?php
mysql_connect("localhost","root","");
mysql_select_db("dbTaggies");
$q=mysql_query("SELECT count(*) as 'return' FROM users
WHERE name='$_POST[user]' AND password ='$_POST[pass]'");
while($e=mysql_fetch_assoc($q))
{
$output[]=$e;
}
print(json_encode($output));
mysql_close();
?>
I'm using this and for me always works fine:
DefaultHttpClient client = new DefaultHttpClient();
JSONObject json = null;
String resoult = "";
try
{
HttpPost postRequest = new HttpPost("XXXXXXXXXXXXXXXXXX");
HttpResponse postResponse = client.execute(postRequest);
HttpEntity postResponseEntity = postResponse.getEntity();
if (postResponseEntity != null)
resoult= EntityUtils.toString(postResponseEntity);
json = new JSONObject(resoult);
}
catch(Exception e)
{
}
The problem is solved.
PHP files were saved in UTF-8 WITH BOM, the solution was saving the files in UTF8 no BOM and the initial character in the POST response was removed.

Categories