Pass Class Object to MultiPart Entity in android - android

I have to work on an application where i need to send the class object as Parameter using Multipart Entity along with a file. I have checked that the Multipart addpart method doesn't accept an Object to post to Web Api.Below is the Code i have tried. Any Suggestions on how to pass the object would be great.
HttpPost post = BaseActivity.getHttpPost("MyURL");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,"",Charset.defaultCharset());
try {
ServiceJobFileModel sjfm = new ServiceJobFileModel();
sjfm.setFileExtension(myfileextension);
sjfm.setCapturedDate(captdate);
sjfm.setFileName("/pathtofile/filename.extension");
File f = new File(sjmf.getFileName());
entity.addPart("file", new FileBody(f));
entity.addPart("serviceJobFileModel", sjfm); // Compiler Error
post.addHeader("Accept-Encoding", "gzip, deflate");
post.setEntity(entity);
} catch (UnsupportedEncodingException e) {
Log.v("encoding exception","E::: "+e);
e.printStackTrace();
}
The Web Api is developed in Dotnet which is why the windows mobile app has sent the parameters as
var parameters = new ServiceJobFileModel()
{
FileExtension = serviceJobFileModel.FileExtension,
CapturedDate = serviceJobFileModel.CapturedDate,
ServiceJobNumber = serviceJobFileModel.ServiceJobNumber
};
content.Add(new StreamContent(filestream), "file", Path.GetFileName(fileName));
content.Add(new ObjectContent<ServiceJobFileModel>(parameters, new JsonMediaTypeFormatter()), "serviceJobFileModel");

IMHO you should serialize your object in a text format like JSON or XML and then use a StringBody to send it.

Related

How to POST list of objects as JSON from Android client to PHP REST API?

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();

Recieving HTML file as responce instead of JSON Object through get request

I am developing an android app where user logs on to his/her account. After logging in I will receive XSRF token and Laravel Session Id to recognise the specific user. I have to send these tokens for every request I send to the API's to get the appropriate information. But when I am sending the required details as shown in the image, I am getting HTMl file as response instead of getting JSON Object. I was seriously stuck at this problem. Correct Solution may take forward the whole app.
class RegisterConnection extends AsyncTask<String,String,JSONObject> {
protected JSONObject doInBackground(String... arg0) {
JSONObject output = new JSONObject();
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 5000); //Timeout Limit
HttpResponse response = null;
try {
HttpGet get = new HttpGet(statsURL);
get.setHeader("Accept", "application/json");
CookieStore store = new BasicCookieStore();
BasicClientCookie cookie1 = new BasicClientCookie("XSRF-TOKEN", XSRF);
BasicClientCookie cookie2 = new BasicClientCookie("laravel_session", laravel);
store.addCookie(cookie1);
store.addCookie(cookie2);
client.setCookieStore(store);
response = client.execute(get);
if(response!=null){
InputStream in = response.getEntity().getContent();
String resultstring = Utilities.convertStreamToString(in);
Log.i("Result1", resultstring);
output = new JSONObject(resultstring);
Log.i("Result2", output.toString());
}
} catch(Exception e) {
e.printStackTrace();
try {
output.put("sai","error");
Log.i("MainActivity", output.toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
return output;
}
return output;
}
These are the server requirements
http://imgur.com/OY9Q673
This is the Output received
http://imgur.com/IB5AEcT
As far as I can tell, there is nothing wrong with your Android client code.
You are getting HTML from the server so the main reason could be that your Laravel server is rendering the views and sending you back html instead of JSON. Instead of rendering the views on the server, you should send JSON response on your Laravel server side.
Add Jsoup dependency in your gradle file
implementation 'org.jsoup:jsoup:1.11.2'
Document document = Jsoup.parse("http://imgur.com/IB5AEcT");
Elements el = doc.select("button");
Log.i("..........",""+el.attr("data-invite-details"));
Jsoup tutorial
http://jsoup.org/apidocs/org/jsoup/Jsoup.html

How to make JSONarray of object using MultipartEntity?

I have to post such json using MultipartEntity.
{
arrayName":[
{
// object one
},
{
// object two
}]
}
I don't get an idea how to make such structure once posting multipartEntity object, what i have tried so far is.
MultipartEntity entity = new MultipartEntity();
entity.addPart("key","value");
.....
.....
..... all keys
httppost.setEntity(entity);
Is there any way so i can make MultipartEntity array or what?
NOTE: for separate posting one json object it work very fine. I just want to learn how to create JSONarry format, once posting with MultipartEntity.
You have to convert your json array to string.
Use Gson Library for that. Gson
Now you just have to use like this.
Whatever you model is so
ArrayList<CustomClass> objects = new ArrayList<>();
objects.add(object);
objects.add(object);
and then just use gson.
String stringToPost = new Gson().toJson(objects);
then add multipart this string as
Stringbody
Server side will deserialize String to Json Array.
Also you can add file as filebody in multipart.
This is an example to upload image and JSONArray using MultipartEntity-- lib:org.apache.http.entity.mime
List students = getStudentList();
MultipartEntity studentList = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int i=0; i<students.size();i++){
try {
studentList.addPart("studentList[][name]", new StringBody(String.valueOf(students.get(i).getName())));
studentList.addPart("studentList[][addmission_no]", new StringBody(String.valueOf(students.get(i).getAddmissionNo)));
studentList.addPart("studentList[][gender]", new StringBody(String.valueOf(students.get(i).getGender)));
File photoImg = new File(students.get(i).getImagePath());
studentList.addPart("studentList[][photo]",new FileBody(photoImg,"image/jpeg"));
}catch(Exception e){
e.getMessage();
}
}
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.addHeader("X-Auth-Token", mUserToken);
post.setEntity(studentList);
org.apache.http.HttpResponse response = null;
try {
response = client.execute(post);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = response.getEntity();
JSONObject myObject;
try {
String result = EntityUtils.toString(httpEntity);
// do your work
} catch (IOException e) {
e.printStackTrace();
}

parse Multipart response in Android

I'm sending images and json text from the android client to a tomcat server and the other way around by using Multipart HttpPost's. Sending a Multipart Entity to the server is no big deal, because you can process the parts easily using request.getPart(<name>). But at the client side you can only access the response as a Stream. So I end up appending both, the JSON string and the image to the same ServletOutputStream and have to parse them by hand on the client side. I found apache-mime4j in the web but its hardly documented and I cant find a single example how to use it.
On the server side I build the response like this:
ServletResponse httpResponse = ctx.getResponse();
ResponseFacade rf = (ResponseFacade) httpResponse;
rf.addHeader("Access-Control-Allow-Origin", "*");
rf.addHeader("Access-Control-Allow-Methods", "POST");
rf.addHeader("content-type", "multipart/form-data");
httpResponse.setCharacterEncoding("UTF-8");
MultipartResponse multi = new MultipartResponse((HttpServletResponse) httpResponse);
ServletOutputStream out = httpResponse.getOutputStream();
multi.startResponse("text/plain");
out.println(CMD + "#" + content);
multi.endResponse();
multi.startResponse("image/jpeg");
out.write(data);
multi.endResponse();
multi.finish();
ctx.complete();
And on the client side on Android I want to access the text and the image data:
InputStream is = response.getEntity().getContent();
MimeStreamParser parser = new MimeStreamParser();
MultipartContentHandler con = new MultipartContentHandler();
parser.setContentHandler(con);
try {
parser.parse(is);
String json = con.getJSON(); //get extracted json string
byte[] imgBytes = con.getBytes(); //get extracted bytes
} catch (MimeException e) {
e.printStackTrace();
} finally {
is.close();
}
class MultipartContentHandler implements ContentHandler{
public void body(BodyDescriptor bd, InputStream in) throws MimeException, IOException {
//if MIME-Type is "text/plain"
// process json-part
//else
// process image-part
}
In the method body(BodyDescriptor bd, InputStream in) my whole response is treated as text\plain mime type. So I finally have to parse every byte manually again and the whole apache-mime4j is useless. Can you tell me what I am doing wrong? Thanks!
Ok i finally solved it myself. No here's what i did:
First I need to create a multipart/mixed Response at the server side. It can be done using apache-mime-4j API:
ServletResponse httpResponse = ctx.getResponse();
ResponseFacade rf = (ResponseFacade) httpResponse;
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("multipart/mixed");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "SEPERATOR_STRING",Charset.forName("UTF-8"));
entity.addPart("json", new StringBody(CMD + "#" + content, "text/plain", Charset.forName("UTF-8")));
entity.addPart("image", new ByteArrayBody(data, "image/jpeg", "file"));
httpResponse.setContentLength((int) entity.getContentLength());
entity.writeTo(httpResponse.getOutputStream());
ctx.complete();
Now at the client side to access the MIME-Parts of the HttpResponse I use the javax.mail API.
ByteArrayDataSource ds = new ByteArrayDataSource(response.getEntity().getContent(), "multipart/mixed");
MimeMultipart multipart = new MimeMultipart(ds);
BodyPart jsonPart = multipart.getBodyPart(0);
BodyPart imagePart = multipart.getBodyPart(1);
But you can't use the native API, instead take this one http://code.google.com/p/javamail-android/
Now you can proceed handling your individual parts.
It is also possible with apache-mime-4j:
HttpURLConnection conn = ...;
final InputStream is = conn.getInputStream();
try {
final StringBuilder sb = new StringBuilder();
sb.append("MIME-Version: ").append(conn.getHeaderField("MIME-Version")).append("\r\n");
sb.append("Content-Type: ").append(conn.getHeaderField("Content-Type")).append("\r\n");
sb.append("\r\n");
parser.parse(new SequenceInputStream(new ByteArrayInputStream(sb.toString().getBytes("US-ASCII")), is));
} catch (final MimeException e) {
e.printStackTrace();
} finally {
is.close();
}

Calling Rest webservice in Android

I have Java web application server [ acts like server ].
In Android application, using httppost i have calling the restwebserive server.
My calling is hit the webservice with the response code 200.
Now i want to pass the java class object as like parameter.
sample java class:
public Class Sample{
public String Username;
public String getUsername()
{
return Username;
}
public void setUsername(String user){
this.Username = user;
}}
Used code :[ Is not passing my class object to server ]
Sample sam = new Sample();
sam.setUsername("Test");
JSONObject json = new JSONObject();
json.put("Sample", sam);
StringEntity se = new StringEntity(json.toString());
Httppostrequest.setEntity(se);
when i debugging the server the sample object parameter input is empty.[Not passed properly]
How to pass the class object via http post in android?
Please help me on this.
Thanks in advance,
Kums
if you use apache library you can do it one line
JSONSerializer.toJSON(sam);
otherwise i think you have to send it as
Sample sam = new Sample();
sam.setUsername("Test");
JSONObject json = new JSONObject();
json.put("sample", sam.getUserName());
StringEntity se = new StringEntity(json.toString());
Httppostrequest.setEntity(se);
Here is a code snippet
public void callWebService(String q){
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(URL + q);
request.addHeader("deviceId", deviceId);
ResponseHandler<string> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
Log.i(tag, result);
} // end callWebService()
}
Use this method to call your webservice
I have built a library for doing async requests, you can send parameter requests as www.somedomain.com/action?param1="somevalue" etc.. and also there is the option to use string body.
https://github.com/darko1002001/android-rest-client
Check it out, it might be helpful.

Categories

Resources