I am trying to post some data form android app to Laravel rest api. The data is converted and posted as jsonArray.
The code works fine in HttpRequester (Firefox extension) but throws 500 Internal Server Error when posted from Android.
Android
public static int check(String token) throws IOException
{
int flag;
String response=Constants.EMPTY_STRING;
URL mUrl=null;
HttpURLConnection mConnection=null;
String message="";
JSONObject myObject1 = new JSONObject();
JSONObject myObject2 = new JSONObject();
JSONObject myObject3 = new JSONObject();
JSONArray myArray = new JSONArray();
JSONObject mySentObject = new JSONObject();
try {
myObject1.put("id","01");
myObject1.put("name","Ali Jibran");
myObject1.put("date","2016-04-01");
myArray.put(myObject1);
myObject2.put("id","02");
myObject2.put("name","Imran Raja");
myObject2.put("date","2016-05-03");
myArray.put(myObject2);
myObject3.put("id","03");
myObject3.put("name","M.Quddus Raja");
myObject3.put("date","2015-06-01");
myArray.put(myObject3);
//mySentObject.put("data",myArray.toString());
//message = mySentObject.toString();
message = myArray.toString();
} catch (JSONException e) {
e.printStackTrace();
}
//String mQuery = Constants.APP_TOKEN_KEY
// + Constants.EQUALS + token + Constants.AMPERSAND + "posted=" + message;
String mQuery = "posted=" + message;
Log.d(Constants.APP_TAG,"================== Checking =================" );
Log.d(Constants.APP_TAG, "check -> Query is : " + mQuery);
mUrl = new URL(Constants.APP_URL + "info?" + mQuery);
mConnection = (HttpURLConnection) mUrl.openConnection();
mConnection.setDoInput(true);
mConnection.setDoOutput(true);
//mConnection.setFixedLengthStreamingMode(message.getBytes().length);
mConnection.setConnectTimeout(5000);
mConnection.setInstanceFollowRedirects(false);
mConnection.setRequestMethod(Constants.POST);
mConnection.setRequestProperty("Content-type", "application/json");
mConnection.setRequestProperty("charset", "utf-8");
//Write Post Data
DataOutputStream wr = new DataOutputStream(mConnection.getOutputStream());
wr.writeUTF(message.getBytes().toString());
wr.flush();
wr.close();
flag = mConnection.getResponseCode();
if (flag != 200) {
Log.d(Constants.APP_TAG,"Failure " + flag + " " + mConnection.getResponseMessage());
}
if (flag == 200){
response = readData(mConnection);
try
{
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.has("reply"))
Log.d(Constants.APP_TAG,"Reply received -> " + jsonObject.getString("reply"));
if(jsonObject.has("newmercs"))
Log.d(Constants.APP_TAG,"Data received -> " + jsonObject.getString("newmercs"));
if(jsonObject.has("count"))
Log.d(Constants.APP_TAG,"Count received -> " + jsonObject.getString("count"));
} catch (JSONException e)
{
e.printStackTrace();
}
}
return flag;
}
Laravel 5.0
Route::post('info',function(){
//$newmercs = json_decode(Input::get('posted'),true);
$newmercs = json_decode(Input::get('posted'));
$reply = "";
$count = 0;
foreach ($newmercs as $newmerc){
$count++;
}
if ($count > 0){
$reply = 'Success';
}else {
$reply = 'Failure';
}
return response()->json(compact('newmercs','reply','count'));
});
This is what i should get (HttpRequester also returns the same)
{
"newmercs":
[
{
"date": "2016-04-01",
"id": "01",
"name": "Ali Jibran"
},
{
"date": "2016-05-03",
"id": "02",
"name": "Imran Raja"
},
{
"date": "2015-06-01",
"id": "03",
"name": "M.Quddus Raja"
}
],
"reply": "Success",
"count": 3
}
You can use Retrofit Lib to communicate with your API, it's so much easier.
Retrofit doc : http://square.github.io/retrofit/
Have a great day
Related
I'm unable to fetch from this type of JSON, I'm confused in how to get data from inside of JsonObject, I got the value of "dealer_name", "phone_no" and "address" but I'm not getting the value of other.
This is my Solution.
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
urlLink, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("suraj", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
String name = response.getString("dealer_name");
String phone_no = response.getString("phone_no");
String add = response.getString("address");
JSONObject phone = (JSONObject) response.get(String.valueOf(i));
String acc_name = phone.getString("auto_dealer_id");
String acc_price = phone.getString("accessory_price");
jsonResponse = "";
jsonResponse += "dealer_name: " + name + "\n\n";
jsonResponse += "dealer_phone: " + phone_no + "\n\n";
jsonResponse += "dealer_add: " + add + "\n\n";
jsonResponse += "acc_name: " + acc_name + "\n\n";
jsonResponse += "acc_price: " + acc_price + "\n\n";
}
txt.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(Activity3.this).add(jsonObjReq);
}
This is my JSON data:-
{
"auto_dealer_id": "1",
"dealer_name": "RAJ MOTORS",
"phone_no": "9004296356",
"address": "THANE WEST 40002",
"0": {
"auto_dealer_accessory_id": "1",
"auto_dealer_id": "1",
"accessory_name": "CAR OILING",
"accessory_price": "40"
},
"1": {
"auto_dealer_accessory_id": "2",
"auto_dealer_id": "1",
"accessory_name": "CAR WASHING",
"accessory_price": "40"
},
"2": {
"auto_dealer_gallery_id": "1",
"auto_dealer_id": "1",
"image": "1.jog",
"status": "1",
"sort": "1",
"added_date": "0000-00-00 00:00:00"
}
}
try this code:
try
{
String jsonString="";//your json string here
JSONObject jObject= new JSONObject(jsonString);
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
Log.v("key Items", key);
JSONObject innerJObject = jObject.getJSONObject(key);
Iterator<String> innerKeys = innerJObject.keys();
while( innerKeys.hasNext() )
{
String innerKkey = keys.next();
String value = innerJObject.getString(innerKkey);
Log.v("key = "+key, "value = "+value);
}
}
}
catch (JSONException e){
e.printStackTrace();
}
but it is better approach to convert you JsonObject "1","2"... to JsonArray
Since you want to get json object inside json object,
here you can get
JSONObject number = response.getJSONObject("1");
number.getString("auto_dealer_accessory_id")
and so on.
But there are some better approaches as well. Use Gson and also improve your data structure coming from server. using an array is better option and don't forget to check if the object or string exists before you try to get a value. you can use
jsonObject.has("key")
Try this:
ArrayList acc_name = new ArrayList();
...
...
try
{
JSONObject obj=new JSONObject(responseString);
String name = obj.getString("dealer_name");
String phone_no = obj.getString("phone_no");
String add = obj.getString("address");
Iterator<String> keys = obj.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONObject innerJObject = obj.getJSONObject(key);
Iterator<String> inKeys= innerJObject .keys();
while( inKeys.hasNext() )
{
String inKeys= keys.next();
acc_name.Add(innerJObject .getString(inKeys);
..
}
}
}
catch (JSONException e)
{ e.printStackTrace(); }
I have received a string value from JSON, but when I add that JSON value to a JSON array it gives an error stating that it can not convert String value to JSONArray. Please help me.
In the response there are a 3 values in "Value"
protected class AsyncMenuRate extends
AsyncTask<ForGettingRate, JSONObject, JSONObject> {
JSONObject jsonObj = null;
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
jsonObj = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected void onPostExecute(JSONObject objects) {
try {
//String ss= objects.getString("Value").;
JSONArray jarray=objects.getJSONArray("Value");
//jarray = new JSONArray(ss);
for (int i = 0; i < jarray.length(); i++) {
jsonObj = jarray.getJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(DisplayActivity.this, "Successfully inserted...", Toast.LENGTH_LONG).show();
}
}
This is a function that I have return value:
String menuTotal = "0";
String item_rate;
public String MenuRate(int t_id, String menunameoflist) {
if (dbConnection.State.ToString() == "Closed") {
dbConnection.Open();
}
if (db.ChkDb_Value("select * from table_status where table_type='" + "A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select rate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else if (db.ChkDb_Value("select * from table_status where table_type='" + "Non A/C" + "'and t_id='" + t_id + "'"))
item_rate = db.getDb_Value("select non_ACrate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
else
item_rate = db.getDb_Value("select driverRate from menu where m_name='" + menunameoflist + "' ").ToString(); // get the item rate from the tbl
//menuRate = db.getDb_Value("select menu_id From menu where m_name='" + getMenuname + "'");
dbConnection.Close();
return item_rate;
}
This is the JSON format:
{
"name": "MenuRate",
"parameters": [
{
"name": "t_id",
"type": "int32"
},
{
"name": "menunameoflist",
"type": "string"
}
],
"returnvalue": "string"
}
This is function that I have get a response from JSON:
public JSONObject MenuRate(int t_id, String menunameoflist) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface","RestAPI");
o.put("method", "MenuRate");
p.put("t_id",mapObject(t_id));
p.put("menunameoflist",mapObject(menunameoflist));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
First your MenuRate method returns String not JSONObject. So you had to get that as String and convert it into JSONObject, as shown below.
#Override
protected JSONObject doInBackground(ForGettingRate... params) {
RestAPI api = new RestAPI();
try {
String jsonString = api.MenuRate(params[0].getTableId(), params[0].getMenulist());
return new JSonObject(jsonString);
} catch (Exception | JsonException e) {
// TODO Auto-generated catch block
Log.d("AsyncCreateUser", e.getMessage());
}
return jsonObj;
}
Don't forgot to add the JsonException, no problem some how it will ask to add the exception.
Now the string value is converted to JSON, so now you can fetch the values and while fetching use opt instead of get like optJsonArray("key") instead of getJsonArray("key") by this way we will get null value instead of exception, if the key is not present in the JSON.
Now coming to the "value" key access in your JSON response. Below is the JSON value which you have provided,
{
"name": "MenuRate",
"parameters": [{
"name": "t_id",
"type": "int32"
}, {
"name": "menunameoflist",
"type": "string"
}],
"returnvalue": "string"
}
In your question you have mentioned that you need access a json array with the key "Value". But in this there is no array with key "Value". So the below code will explain you how to access the "name" string value and "parameters" Json array.
try {
//Name String value...
String name = objects.optString("name");
//Parameter Json Array...
JSONArray parameterarray =objects.optJSONArray("parameters");
for (int i = 0; i < parameterarray.length(); i++) {
JsonObject jsonObj = parameterarray.optJSONObject(i);
}
} catch (Exception e) {
e.printStackTrace();
}
Hope this is helpful :)
How i can convert my code into "utf-8"?i have a text file which name is "textarabics.txt"
and this text file contains utf-8 characters..below is my code please suggest me how i can convert into utf-8?
try {
File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");
FileInputStream stream = new FileInputStream(yourFile);
String jsonStr = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
jsonStr = Charset.defaultCharset().decode(bb).toString();
Log.d("Noga Store", "jString = " + jsonStr);
}
finally {
stream.close();
}
Log.d("Noga Store", "jString = " + jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting data JSON Array nodes
JSONArray data = jsonObj.getJSONArray("data");
// looping through All nodes
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
// String duration = c.getString("duration");
int duration = c.getInt("duration");
// tmp hashmap for single node
/* HashMap<String, String> parsedData = new HashMap<String, String>();
// adding each child node to HashMap key => value
parsedData.put("id", id);
parsedData.put("title", title);
parsedData.put("duration", duration);*/
textnames.add(title);
textduration.add(duration);
// textnames.add(duration);
// do what do you want on your interface
}
} catch (Exception e) {
e.printStackTrace();
}
This is my "textarabics.txt" file
{
"data": [
{
"id": "1",
"title": "تخطي نوجا نوجا أخبار واستعراض السوق",
"duration": 10
},
{
"id": "2",
"title": "أحدث نوجا الأخبار وآخر المستجدات",
"duration": 3
},
{
"id": "3",
"title": "نوجا الأخبار وآخر المستجدات",
"duration": 5
},
{
"id": "4",
"title": "لا تحتوي على تطبيقات وجد نوع الكلمة",
"duration": 7
},
{
"id": "5",
"title": "تحتاج إلى إعادة تشغيل التطبيق لاتخاذ تغييرات الخط. هل تريد إعادة التشغيل الآن",
"duration": 4
}
]
}
Instead of using Charset.defaultCharset() you can use Charset.forName("UTF-8"). Also you are missing a JSONTokener that you should use with your input. This is based on your code:
try {
File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");
FileInputStream stream = new FileInputStream(yourFile);
String jsonStr = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
jsonStr = Charset.forName("UTF-8").decode(bb).toString();
Log.d("Noga Store", "jString = " + jsonStr);
}
finally {
stream.close();
}
Log.d("Noga Store", "jString = " + jsonStr);
// A JSONTokener is needed in order to use JSONObject correctly
JSONTokener jsonTokener = new JSONTokener(jsonStr);
// Pass a JSONTokener to the JSONObject constructor
JSONObject jsonObj = new JSONObject(jsonTokener);
// Getting data JSON Array nodes
JSONArray data = jsonObj.getJSONArray("data");
// looping through All nodes
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
// String duration = c.getString("duration");
int duration = c.getInt("duration");
// tmp hashmap for single node
/* HashMap<String, String> parsedData = new HashMap<String, String>();
// adding each child node to HashMap key => value
parsedData.put("id", id);
parsedData.put("title", title);
parsedData.put("duration", duration);*/
textnames.add(title);
textduration.add(duration);
// textnames.add(duration);
// do what do you want on your interface
}
} catch (Exception e) {
e.printStackTrace();
}
A more efficient way of dealing with the file would be to wrap the FileInputStream in a InputStreamReader and using InputStreamReader with charset constructor appending the characters to read to a StringBuffer.
Another solution - working on Android 11+ is
try {
File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");
FileInputStream stream = new FileInputStream(yourFile);
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
try {
JsonReader jsonReader = new JsonReader(reader);
jsonReader.beginObject();
jsonReader.nextName();
jsonReader.beginArray();
while (jsonReader.hasNext()) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equalsIgnoreCase("id")) {
String id = jsonReader.nextString();
// use the id parameter in some way
System.out.println("id = " + id);
}
if (name.equalsIgnoreCase("title")) {
String title = jsonReader.nextString();
// use the title parameter in some way
System.out.println("title = " + title);
}
if (name.equalsIgnoreCase("duration")) {
// use the duration parameter in some way
int duration = jsonReader.nextInt();
System.out.println("duration = " + duration);
}
}
jsonReader.endObject();
}
jsonReader.endArray();
jsonReader.endObject();
} finally {
try {
if (reader != null) {
reader.close();
}
reader = null;
} catch (Exception e) {
// TODO: handle exception
}
try {
if(stream != null) {
stream.close();
}
stream = null;
} catch (Exception e) {
// TODO: handle exception
}
}
} catch (Exception e) {
e.printStackTrace();
}
i made a asynctask routine to comunicate to all my webservices that looks as follows:
protected String[] doInBackground(String... params) {
String parameterString = params[0];
// effectieve http request met de parameters toegevoegd
HttpClient client = new DefaultHttpClient();
HttpGet aanvraag = new HttpGet(server + parameterString);
// foutanalyse van de http request
try
{
HttpResponse antwoord = client.execute(aanvraag);
StatusLine statuslijn = antwoord.getStatusLine();
int statuscode = statuslijn.getStatusCode();
if(statuscode != 200){
Log.i("statuscode verzending", "statuscode= "+ statuscode);
return null;
}
InputStream jsonStream = antwoord.getEntity().getContent();
BufferedReader reader= new BufferedReader(new InputStreamReader(jsonStream));
StringBuilder builder = new StringBuilder();
String lijn;
while((lijn = reader.readLine())!= null){
builder.append(lijn);
}
String jsonData = builder.toString();
// hier beginnen we met de json data te ontmantelen
JSONArray json = new JSONArray(jsonData);
String[] data = new String[35];
Log.i("jsonparser", "lengte geretourde data " + json.length());
for (int i = 0; i < json.length(); i++)
{
data[i] = json.getString(i).toString();
}
return data;
}
catch (ClientProtocolException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
i use the routine everytime i connect to a webservice for my app, (i have about 15 of them)
all these webservices are made (and used) by the programs my software supplier made
now i would like to connect to them with my android app
some of them are working
others don't
what i found out already in my search for this failure:
some jsondata is returned in the form of:
[
"42416",
" ",
" ",
" "
]
other webservices return data as:
true
but the ones i am strugling with the most are looking like:
{
"z00": "1 ",
"z01": 10000,
"z02": "18/06/2010",
"z03": "A",
"z04": "0000",
"z05": 7735,
"z06": "VANNUYSE BVBA",
"z07": "DEEFA",
"z08": 17170,
"z09": "AFLEVEREN HELI IN GEBRUIK",
"z10": "0000",
"z11": "8770 ",
"z12": "INTER ",
"z13": "HELI ",
"z14": "CPCD25 - C240 ",
"z15": "48182 ",
"z16": "",
"z17": "N",
"z18": "0030",
"z19": 0,
"z20": "X",
"z21": " ",
"z22": "J",
"z23": "",
"z24": 0,
"z25": "22/06/2010",
"z26": 16854,
"z27": 0,
"z28": "AFLEVEREN IN GEBRUIK",
"z29": " "
}
how should i form my asynctask routine so she is able to work for all routines?
because my routine works fine now for the first type of data but at 3th type i get an error (didn't tried yet for 2nd type) :
JSONObject cannot be converted to JSONArray
thanks already for al your help guys
If you don't know what(jsonObject or jsonArray) is coming, you may try something like this:
try {
JSONObject jsonObject = new JSONObject(jsonData);
// handle jsonObject
} catch (JSONException e) {
// Try to parse it to a JSONAray.
// Also you can check the exception message here to determine if jsonArray conversion is wanted
try {
JSONArray jsonArray = new JSONArray(jsonData);
// handle jsonArray
} catch (JSONException e) {
// something which is not JsonObject or JsonArray!
}
}
Or try this:
Object jsonAsObject = new JSONTokener(jsonData).nextValue();
if (jsonAsObject instanceof JSONObject) {
// it is JSONObject
JSONObject jsonObject = (JSONObject) jsonAsObject;
} else if (jsonAsObject instanceof JSONArray) {
// it is JSONArray
JSONArray jsonArray = (JSONArray) jsonAsObject;
}
Here is my JSON link, and how it looks:
{
"to": "CAD",
"rate": 1.0223997600000001,
"from": "USD",
"v": 5.1119988000000003
}
I tried this syntax:
JSONObject o = new JSONObject(sourceString);
String from = o.getString("from");
but it didn't work.
You can create a class
public class Abc {
String to;
String rate;
String from;
String v;
}
and then can use below code for parsing
JsonObject obj= gson.fromJson(DATA,Abc.class);
Where DATA will be your gson string.
Are you running it on simulator?
Or if you are ruuning it on device then off and on your internet connection,it will work.
hello Check this Code it give you result in log(error)
protected void getJSONFromURL(String string) {
// TODO Auto-generated method stub
string = "http://rate-exchange.appspot.com/currency?from=USD&to=CAD&q=5";
String is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet Get = new HttpGet(string);
HttpResponse responce = httpclient.execute(Get);
HttpEntity entity = responce.getEntity();
is = EntityUtils.toString(entity, "UTF-8");
Log.e("responce-->", "" + is.toString());
if (!is.toString().equalsIgnoreCase("")) {
JSONObject ob = new JSONObject(is.toString());
String to = ob.getString("to");
Log.e("to", "" + to);
String from = ob.getString("from");
Log.e("from", "" + from);
double rate = ob.getDouble("rate");
Log.e("rate", "" + rate);
double v = ob.getDouble("v");
Log.e("v", "" + v);
}
} catch (Exception e) {
// TODO: handle exception
Log.d("call http :", e.getMessage().toString());
is = null;
}
}
if you are yseing above 3.0 OS then also include this code;
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT>8){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Your Result is over here:
03-19 11:23:22.745: E/responce-->(811): {"to": "CAD", "rate": 1.0220998400000001, "from": "USD", "v": 5.1104992000000005}
03-19 11:23:22.745: E/to(811): CAD
03-19 11:23:22.776: E/from(811): USD
03-19 11:23:22.776: E/rate(811): 1.02209984
03-19 11:23:22.791: E/v(811): 5.1104992000000005