I want to perform following task :
1 > accept input from user and save it
2 > Send this input value with whole json object to server
This is log cat result
see this
http://hmkcode.com/android-send-json-data-to-server/
How to send a JSON object over Request with Android?
USe The following code..
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
Related
Scenario:
REST API: PHP Slim Framework
Android HTTP client library: loopj
I am storing an ITEM as json string in sqlite.
I want to POST this JSON on server. Each item is a record in my SQLite database.
What I am currently doing?
I have JSON with list of objects. I want to POST it to my PHP based REST API.
Here is the code
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Item item = new Item();
try {
item.setOfflineId(Long.parseLong(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setImageLocalPath(itemPayload.getImageLocalPath());
item.setToUpdate(Boolean.parseBoolean(cursor.getString(3).toString()));
item.setDeviceID(cursor.getString(4));
item.setCreatedDate(cursor.getString(5));
//item.setImageBlob(cursor.getBlob(5));
String imageURL = itemPayload.getImageLocalPath();
File imageFile = new File(imageURL);
} catch (Exception e) {
Log.d("Ex", e.getMessage().toString());
}
itemList.add(item);
} while (cursor.moveToNext());
}
}
}catch(SQLException ex){
Log.d("DB", ex.getMessage().toString());
}
The challenge?
When I put the params for post, I also set one Param to File as I want to upload an image file as well. I know how to send one object as JSON. I want to POST the list of items (items having image Files). How to achieve this?
One way is that I do an API POST for each object in the list. Not sure if it is a good way to do it.
Looking for advice.
You can post json using this way
JSONObject json = new JSONObject();
json.put("obj", "obj value");
StringEntity entity = new StringEntity(json.toString());
client.post(context, url, entity, "application/json",
responseHandler);
Use this code to send Json data
try{
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("projectid","1");
jsonObject.accumulate("cnumber", "8983899383");
jsonObject.accumulate("address","IN");
jsonObject.accumulate("companyid","5");
jsonObject.accumulate("uploadimage","");
jsonObject.accumulate("id","9")
data = jsonObject.toString();
Log.d("json data",data);
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(CHECK_WEBSERVICE_URL);
StringEntity se = new StringEntity(data);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
I am posting data in json Format to server but I am getting response status 404,
please let me know how to fixed,
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", uemail);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
Log.e("value send",json);
StringEntity se = new StringEntity(json.toString());
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
thanks
I have a HttpPost Request and I need to set multiple entities for it. I know that setEntity is used to set single entity.
ObjectMapper mapper = new ObjectMapper();
String json = "";
json = mapper.writeValueAsString(object);
StringEntity se = new StringEntity(json);
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
request.setEntity(se);
But how to set multiple entitiesin the request?
When sending the POST request using UrlEncodedFormEntity which takes List as input parameter along with the key, my request gets converted in the form of [key={json}] .
But the request i want to send should be in the form of key={json} , i.e not as List.
So, is there any alternative for the given method when using POST?
notes: webservice is working fine , and since it is json ,i cannot use Soap .
i ve tested it using POSTman and webservices are WCF(if thats of any use..)
if any code is required , please mention it.
Thanks in advance.
Edit code:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(URL);
List<NameValuePair> value=new ArrayList<NameValuePair>();
value.add(new BasicNameValuePair("data",string));
//here it passes as List and here is where i want an alternate method
// by which i can send parameter as JSONobject
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(value);
request.setEntity(entity);
HttpResponse response = client.execute(request);
HttpEntity entity2 = response.getEntity();
if(entity2.getContentLength() != 0) {
Reader tapReader = new InputStreamReader(response.getEntity().getContent());
char[] buffer = new char[(int) response.getEntity().getContentLength()];
tapReader.read(buffer);
tapReader.close();
JSONObject tapJsonObj = new JSONObject(buffer);
I use HttpClient in android to send post request:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(hostNameCollection);
StringEntity se = new StringEntity(jsonObj.toString());
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
request.setEntity(se);
HttpResponse response = client.execute(request);
Log.v("HttpLogClient.logJSONObject", "wyslano JSON");
and I'dont know how I can receive JSON object on my Java EE servlet.
you need to read the response body text, then parse as JSON,
String result = EntityUtils.toString(response.getEntity());
JSONObject jo = new JSONObject(result);
read the body of the http post ( server-side ) by getting the a stream object on the body and then reading it.
Once youve read it , convert the bytes to chars and that will be json which you can use to build a json object like a jsonNode using 'jackson' libs.
If you are using plain servlets the json stream is located in the body of the HttpServletRequest : request.getReader() or request.getInputStream();
To make things easier you could use a library handling databinding for you.
Have a look at Genson http://code.google.com/p/genson/.
YouClass object = new Genson().deserialize(request.getReader(), YourClass.class);
// or to a plain map
Map<String, Object> map = genson.deserialize(request.getReader(), Map.class);