How to attach a file to the post url in Android - android

I am developing a Helpdesk application, in this app I am able to read and reply for the tickets sent by the customer. Now I got a requirement, I have to upload a file also. I have a post url to reply for the ticket, I will use Namevaluepairs to attach message with the url..
nameValuepair("id",ticketId);(nameValuepair is the instance of BasicNameValuePair)
nameValuepair("subject",subject);
nameValuepair("reply",message);
If file is not there then it will be like the above code. If file is there I one more parameter comes for file. What I have to do is to attach a file and encode it and then include it into Namevaluepair...
nameValuepair("file",encodedfile);
How can I Upload the file to this app and encode it.
I got some resources to attach a file to the default android email client using email intent, that was not helpful for me.
Thanks in Advance

Uploading a file is more complicated than adding a name-value pair. You need to get the output stream of the request and write the file. You can find an example here.

Use the Http client by Apache and its POST method:
DefaultHttpClient httpclient = appContext.GetHttpClient();
HttpPost httppost = new HttpPost("your.url.com");
httppost.setEntity(new FileEntity(yourFile, PLAIN_TEXT_TYPE));
HttpResponse response = httpclient.execute(httppost);
InputStream responseStream = new ByteArrayInputStream(responseString.getBytes("UTF-8"));

Related

How to send image/pdffile from android to android with database

I want to try developing an android application that can send image/pdfFile from android to android device. For example i have a list of patients. when i click an item it will go to send file to patient that i have clicked. Then the sent file will be stored in database. and will serve as sent file history. Just like an instant messaging. I found an example of instant messaging but this only sending texts not images/files
here AndroidIM
Could anyone convert it to sending images?I really don't know how. Or just link me to some tutorial in sending images/files to another device. I am using also database for storing history of sent files.
send the image to you PHP backend using the Http MultiPart Request like the following :
try{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(imagePath);
ContentBody encFile = new FileBody(file,"image/png");
entity.addPart("images", encFile);
request.setEntity(entity);
}catch(Exception e ){
}
and please give me some feedback .
Hope That Helps .

Android web service, REST or KSOAP2 or get/post

As of now, if I have to store something from Android to the server, I make an HTTP request of a GET URL, with data in the form of parameter values. On the server side, I use PHP to extract the parameter values and store them in database.
Similarly, if I want to get something from the server to Android, I post a JSON string on the webpage using PHP. Then I read it in Android using HTTP request, convert the string to JSON and then use the data.
This method of PHP-MySQL-Android-JSON is very easy but not secure. Suppose I want to store the score of player from my game in Android to the server's database, it is easy to execute some URL like www.example.com/save_score.php?player_id=123&score=999 from Android. But anyone can update his score if he comes to know the php file name and names of parameters, by simply typing this URL in a browser.
So what is the correct method of interacting with a server (my server supports PHP but not Java)?
I have heard about RESTful and KSOAP2, but know nothing about them. Can you please explain them a bit in lay man language (reading the proper definitions didn't help me)? What are these used for?
What is the best way to send score to the server? Any tutorial link would be great.
Thanks.
Edit 1:
I don't use proguard to obfuscate my code for several reasons. So anyone can reverse engineer the apk, look into the code, find the URL to update the score, write his own POST method and update his score. How can I stop this from happening?
Use POST method to post data from android and get it in php. e.g. use this method to send your data in json formate , which will not be showing in url.
public static String sendRequest(String value, String urlString) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString);
httppost.setHeader( "Content-Type", "application/json");
//value = "";
StringEntity stringEntity = new StringEntity(value);
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
httppost.setEntity(stringEntity);
HttpResponse response = httpclient.execute(httppost);
String responseString = convertStreamToString(response.getEntity().getContent());
return responseString;
} catch (Exception e) {
Log.d("check", ""+e.getMessage());
return ERROR_SERVICE_NOT_RESPONDE;
}
}
And call this method like this.
sendRequest({"player_id":1,"score":123}, "www.example.com/save_score.php");
And get json body in php and parse it.
I think you should read more documents about RESTful, Http POST and GET before starting. Your example url is GET method. It should be used for getting public information or query data. If you want to change something in server side, you should use POST method, it is more security than GET.
My recommend is using RESTful because it is painless than SOAP, especially for Android. Here is an example HTTP POST on Android.

HTTP File Download 500 internal server error

I'm writing an Android app which does exactly the same as our iPad app for our company. But I have 1 issue while developing on the android. The app downloads a file from a webserver. It will call an URL like:
https://www.somedomain.com/API/Download.aspx?param1=test&param2=test2 etc...
On the iPad this is working perfectly (I use the ASIHTTPRequest class for this). But on Android it is giving me only problems.
As soon as I want to download the file with the android, it downloads a file with a 500 internal server error HTML document instead of the PDF file.
I've checked the URL's, they look exactly the same as on the iPad.
The only thing I can imagine, is that the file which the user downloads is created "on the fly". So it takes some time (10 or 20 sec) to generate the file, and then the file is being downloaded.
On android I do this:
I have a class which extends:
extends AsyncTask<String, Integer, JSONObject>
In a method, I do this:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
InputStream data = response.getEntity().getContent();
File file = new File(context.getDir("docs", Context.MODE_PRIVATE), FileName);
OutputStream output = new FileOutputStream(file);
ByteStreams.copy(data, output);
Closeables.closeQuietly(output);
But this is giving me a 500 internal server error doc instead of the desired PDF file. What am I missing here? (Sorry, I just started developing for Android so I'm not an expert in this case ;-))
Thanks in advance!
The fact that your response status code from the server is the problem means that this should have nothing to do with the Android stuff and only to do with the request you're sending. I notice, though this might be due to intentional omission, that you're doing a POST request without adding any POST params. Should this be a GET? I notice that the endpoint is an ASPX path with GET params in the query string. Maybe your server is set up to only respond to GET and not POST. How is this being done in the iOS code? Is there no differentiation between GET and POST, or is this abstracted from you via the library you're using?
Ok it works now... Stupid thing... I constantly created a new HttpClient so the session was not stored among connections. That is why the server returned a 500 internal server error because the user was not known by the server...
Thanks everyone for your help though!

Android app getting data from a third-party JSP & Servlet

I'm writing an Android app that should get data from a certain web application. That web app is based on Servlets and JSP, and it's not mine; it's a public library's service. What is the most elegant way of getting this data?
I tried writing my own Servlet to handle requests and responses, but I can't get it to work. Servlet forwarding cannot be done, due to different contexts, and redirection doesn't work either, since it's a POST method... I mean, sure, I can write my own form that access the library's servlet easily enough, but the result is a jsp page.. Can I turn that page into a string or something? Somehow I don't think I can.. I'm stuck.
Can I do this in some other way? With php or whatever? Or maybe get that jsp page on my web server, and then somehow extract data from it (with jQuery maybe?) and send it to Android? I really don't want to display that jsp page in a browser to my users, I would like to take that data and create my own objects with it..
Just send a HTTP request programmatically. You can use Android's builtin HttpClient API for this. Or, a bit more low level, the Java's java.net.URLConnection (see also Using java.net.URLConnection to fire and handle HTTP requests). Both are capable of sending GET/POST requests and retrieving the response back as an InputStream, byte[] or String.
At most simplest, you can perform a GET as follows:
InputStream responseBody = new URL("http://example.com").openStream();
// ...
A POST is easier to be performed with HttpClient:
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("name1", "value1"));
params.add(new BasicNameValuePair("name2", "value2"));
HttpPost post = new HttpPost("http://example.com");
post.setEntity(new UrlEncodedFormEntity(params));
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
InputStream responseBody = response.getEntity().getContent();
// ...
If you need to parse the response as HTML (I'd however wonder if that "public library service" (is it really public?) doesn't really offer XML or JSON services which are way much easier to parse), Jsoup may be a life saver as to traversing and manipulating HTML the jQuery way. It also supports sending POST requests by the way, only not as fine grained as with HttpClient.

http async response for large response

I'm familiar with android HTTPURLConnection and apache HTTPConnection classes and the way they work (they are all synchronous, but I can live with that).
I have a large response with many lines of data comming from the server. It's a JSON response and I can display the data partially before I parsed all the response. Some json parsers allow that (like xcers allows for xml). Do the callbacks and methods related to the two classes mentioned above allow it? When I get the response from HTTPURLConnection upon opening input stream and read, do I open the stream when ALL the data is already there? Or can I open and read it and more that should follow?
Also, is there any http method on android that works with NIO?
With HttpClient, when you open the response stream like this:
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
and start reading, you actually start the downloading and you get new bytes as soon as these are received. You don't wait for everything to get downloaded to start reading.
As far as I know the HttpClient that is bundled with Android is not based on NIO. I don't know of any alternative that does so.
In addition to all of the possible solutions in Ladlestein's comment, there's the simple answer of wrapping all that in an AsyncTask. Here is a sample project demonstrating doing an HTTP request using HttpClient in an AsyncTask.

Categories

Resources