Is it possible to send JSONArray instead of JSONObject via POST? - java

Most of the answers on SO on the subject revolve around sending all your data inside one JSONObject, with the JSONArrays inside.
I would like to do the opposite, if possible.
Here's some code:
JSONObject winnerJSONObject = new JSONObject();
JSONObject loserJSONObject = new JSONObject();
try{
winnerJSONObject.put(Columns.ID.toString(), winner.getId());
winnerJSONObject.put(Columns.NAME.toString(), winner.getName());
winnerJSONObject.put(Columns.SCORE.toString(),winner.getScore());
winnerJSONObject.put(Columns.WINS.toString(), winner.getWins());
winnerJSONObject.put(Columns.LOSSES.toString(), winner.getLosses());
winnerJSONObject.put(Columns.MAX_SCORE.toString(),winner.getMaxScore());
winnerJSONObject.put(Columns.MIN_SCORE.toString(),winner.getMinScore());
loserJSONObject.put(Columns.ID.toString(), loser.getId());
loserJSONObject.put(Columns.NAME.toString(), loser.getName());
loserJSONObject.put(Columns.SCORE.toString(),loser.getScore());
loserJSONObject.put(Columns.WINS.toString(),loser.getWins());
loserJSONObject.put(Columns.LOSSES.toString(),loser.getLosses());
loserJSONObject.put(Columns.MAX_SCORE.toString(),loser.getMaxScore());
loserJSONObject.put(Columns.MIN_SCORE.toString(),loser.getMinScore());
} catch (JSONException e) {
e.printStackTrace();
}
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = null;
try {
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(jsonArray.toString(), HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(winnerJSONObject);
jsonArray.put(loserJSONObject);
Why is this a wrong approach?

Yes it is possible.
Example:
Like if we have our data in arraylist to upload on server, Yo can send it in this way
JsonArray _array = new JsonArray()
for(i = 0; i< _arraylist.size(); i++){
JsonObject obj = new JsonObject();
obj.put(_array.list.get(i).getValue);
_array.put(obj);
}
}

Related

Http post in android with nested associative array

I am trying to send an http post request to a PHP service. Here is an example of how the input may look with some test data
I know that the Java alternative to the PHP associative arrays are HashMaps, but I wonder can this be done with NameValuePairs? What is the best way to format this input and call the PHP service via post request?
Extending #Sash_KP's answer, you can post the nameValuePairs like this too:
params.add(new BasicNameValuePair("Company[name]", "My company"));
params.add(new BasicNameValuePair("User[name]", "My Name"));
Yes this can be done with NameValuePair.You can have something like
List<NameValuePair> params;
//and when making `HttpPost` you can do
HttpPost httpPost = new HttpPost("Yoururl");
httpPost.setEntity(new UrlEncodedFormEntity(params));
//and while building parameters you can do somethin like this
params.add(new BasicNameValuePair("name", "firemanavan"));
params.add(new BasicNameValuePair("cvr", "1245678"));
....
Here's a neat and nice parsing method which you can use.
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
JSONObject jObj = null;
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.e("JSON", 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 jObj;
}
And you can simply use it something like
getJSONFromUrl("YourUrl", params);
Now this is just a basic idea of how you can achieve this using NameValuePair.You will have to need some more workaround to implement exactly as you want, but this should provide you the basic idea.Hope this helps.

Android - How to upload video/image to PHP Server

I am able to post string values to PHP server by using the following code:
public void callWebService(String strEmailList){
HttpResponse response = null;
String responseBody="";
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("stringkey1",
String_Value1));
nameValuePairs.add(new BasicNameValuePair("stringkey2", String_Value2));
nameValuePairs.add(new BasicNameValuePair("stringkey3", String_Value3));
nameValuePairs.add(new BasicNameValuePair("stringkey4", String_Value4));
nameValuePairs.add(new BasicNameValuePair("stringkey5", String_Value5));
nameValuePairs.add(new BasicNameValuePair("stringkey6", Here i need to post Image));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MY URL");
if (nameValuePairs != null)
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handleResponse(responseBody);
}
I am getting responseBody perfectly if i post only string values. In the nameValuePair, I need to post Image to Server. Can anyone help me how to post image using following code.
You can send image to the server as a Multipart entity
public void upload(String filepath) throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// check the response and do what is required
}
For uploading image and Video,,, you need to use MultiPart.First you need to Attach your file in fileBody which later attach in Multipart
public JSONObject file_upload1(String URL, String userid, String topic_id,
String topicname, String filelist, String taglist,
String textComment, String textLink) {
JSONObject jObj = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
FileBody bin = null;
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filelist);
try {
bin = new FileBody(file);
} catch (Exception e) {
e.printStackTrace();
}
reqEntity.addPart("post_data" + i, bin);
reqEntity.addPart("tag", new StringBody("savetopicactivities"));
reqEntity.addPart("user_id", new StringBody(userid));
reqEntity.addPart("text", new StringBody(textComment));
reqEntity.addPart("count",
new StringBody(String.valueOf(taglist.size())));
reqEntity.addPart("topic_id", new StringBody(topic_id));
reqEntity.addPart("topic_name", new StringBody(topicname));
reqEntity.addPart("link", new StringBody(textLink));
httpPost.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
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");
}
json = sb.toString();
System.out.println("json " + json);
try {
jObj = new JSONObject(json);
} catch (Exception e) {
e.printStackTrace();
}
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// return JSON String
return jObj;
}
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (int index = 0; index < nameValuePairs.size(); index++)
{
if (index == nameValuePairs.size()-1)
{
entity.addPart(nameValuePairs.get(index).getName(),
new FileBody(new File(nameValuePairs.get(index)
.getValue())));
} else {
entity.addPart(nameValuePairs.get(index).getName() , new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
String resdata = EntityUtils.toString(resEntity);
System.out.println("DATA :" + resdata);
}
} catch (IOException e) {
e.printStackTrace();
}

App crashes on httGet when attempting to send to Json?

My app crashes on "((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));" and throws an exception "java.lang.ClassCastException:org.apache.http.client.methods.HttpGet".
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
// Prepare JSON to send by setting the entity
((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
response = httpClient.execute(httpGet);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
Activity{
oncreate{
new HitService().execute(addparams here);
}
}
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://your url=" + params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you want to put some data to request body, you have to use HttpPost instead of HttpGet. HttpPost has function for this: setEntity(HttpEntity entity)
Example:
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;

Android JSON parse error with date

Having problems parsing this JSON data in my Android App :
[{"personid":20,"personName":"Ross Gallagher update3","email":"ross_gallagher#rossgallagher.co.uk","birthday":{"date":"2013-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"anniversary":{"date":"1900-01-01 00:00:00","timezone_type":3,"timezone":"America\/Los_Angeles"},"Credit":2}]
The error I am getting is:
W/System.err: org.json.JSONException: Value [{"birthday":{"date":"2013-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"anniversary":{"date":"1900-01-01 00:00:00","timezone":"America\/Los_Angeles","timezone_type":3},"email":"ross_gallagher#rossgallagher.co.uk","personName":"Ross Gallagher update8","Credit":2,"personid":20}] of type org.json.JSONArray cannot be converted to JSONObject
My JSON Parser code is:
public JSONObject getJSONFromUrl(String url)
{
HttpEntity httpEntity = null;
JSONObject respObject = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(httpEntity != null){
try {
respObject = new JSONObject(EntityUtils.toString(httpEntity));
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//....
}
// return JSON
return respObject;
}
All I need is to pull out the Birthday details from this JSON object along with the name, email, credits and anniversary.
Any advice would be appreciated!
Change
respObject = new JSONObject(EntityUtils.toString(httpEntity));
to
respObject = new JSONArray(EntityUtils.toString(httpEntity));
ofcourse respObject has to be an JSONArray
The problem is with your JSON String. You need to remove the square brakets [] .
Square brakets are used to refer array elements. The JSON parser will try to convert it as array object as json data are inside square braket.
Accept my answer if it helps you.
Since the object you are trying to parse is actually a JSONArray and not JSONObject.. So you get JSONObject from that JSONArray like
JSONArray jsonArray = new JSONArray(EntityUtils.toString(httpEntity));
JSONOject jsonObject = jsonArray.getJSONObject(0);
from this jsonObject you would get birthday details...

Android, org.json.jsonarray cannot be converted to jsonobject

I am trying to exchange data with my web server. The code I am having trouble with is:
public void getOnlineData(View view) {
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
int TIMEOUT_MILLISEC = 10000;
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient();
String url = "http://twenty5eight.co.uk/portal/" +
"json/json.php";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("id", jObject.getString("id"));
map.put("name", jObject.getString("name"));
map.put("birthyear", jObject.getString("birthyear"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
Edit: No errors are coming up on the log. The error handler in place is saying "Request failed: org.json.JSONException:Value of type org.json.jsonArray cannot be converted to jsonobject".
From your url, the data is a JSON array. You are trying to create a JSONObject from the String of a JSONArray. It cannot work this way. Create a JSONArray instead.
Also, still from your url, there is no key 'posts' anywhere in your json.

Categories

Resources