Android Series: GET, POST and Multipart POST requests

Posted by admin | Posted in Code Snippets, Mobile Development | Posted on 18-03-2010

12

Today I will describe shortly how to execute http GET and POST request on Android platform.
The code is very simple and straightforward, for post request with attachement, you would have to add apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your build path.

HTTP GET

try {
        HttpClient client = new DefaultHttpClient();  
        String getURL = "http://www.google.com";
        HttpGet get = new HttpGet(getURL);
        HttpResponse responseGet = client.execute(get);  
        HttpEntity resEntityGet = responseGet.getEntity();  
        if (resEntityGet != null) {  
                    //do something with the response
                    Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
                }
} catch (Exception e) {
    e.printStackTrace();
}

HTTP POST

try {
        HttpClient client = new DefaultHttpClient();  
        String postURL = "http://somepostaddress.com";
        HttpPost post = new HttpPost(postURL);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user", "kris"));
            params.add(new BasicNameValuePair("pass", "xyz"));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
            post.setEntity(ent);
            HttpResponse responsePOST = client.execute(post);  
            HttpEntity resEntity = responsePOST.getEntity();  
            if (resEntity != null) {    
                Log.i("RESPONSE",EntityUtils.toString(resEntity));
            }
    } catch (Exception e) {
        e.printStackTrace();
    }

HTTP POST with File attachment

File file = new File("path/to/your/file.txt");
try {
         HttpClient client = new DefaultHttpClient();  
         String postURL = "http://someposturl.com";
         HttpPost post = new HttpPost(postURL);
     FileBody bin = new FileBody(file);
     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
     reqEntity.addPart("myFile", bin);
     post.setEntity(reqEntity);  
     HttpResponse response = client.execute(post);  
     HttpEntity resEntity = response.getEntity();  
     if (resEntity != null) {    
               Log.i("RESPONSE",EntityUtils.toString(resEntity));
         }
} catch (Exception e) {
    e.printStackTrace();
}

Hope this helps!

StumbleuponDelicious

Comments (12)

Hello,

Thanks for the code, nice work!

My environment doesn’t recognize the classes FileBody and MultipartEntity. Are they available in Android?

Thanks again. Cheers

Yes Jalal, you would have to add apache http libraries to make it work: apache-mime4j-0.6.jar and httpmime-4.0.1.jar on your build path.
Thanks for pointing this out.

Hi Krzysztof,

The code works just fine!!! I still need to authenticate the http client but the multipart post is perfect. Thanks.

Cheers,
Jalal

Hello!

I tried to make http post with file attachment and it compiles, but i get java.lang.illegalstateexception. The code executes but doesn’t post anything. I get status 200 back(OK) and the whole website at EntityUtils.toString(resEntity).

Any comments?

Difficult to tell, is it your website? Do you use same file input field on the web form as in the android code? There can be loads of reasons.

Yes it’s my friend’s website. I used firebug(firefox addon) to get the names of the fields.
Here is the html code,could you please take a look.

public void executeMultipartPost() throws Exception {
try {
//InputStream is = this.getAssets().open(“main.xml”); //c:/reno.jpg taka prava pot za winse
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
“http://dev.jurancic.com/krpovej/kranj.php”);

//postRequest.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);

//Log.d(“PARAMETRI PRED ŠTELANJEM”,httpClient.getParams()());
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); //tud nc boljs
//httpClient.getParams().setParameter(“http.socket.timeout”, new Integer(115));
httpClient.getParams().setParameter(“http.useragent”, “Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3″);//

httpClient.getParams().setParameter(“http.protocol.content-charset”, “UTF-8″); //veze
httpClient.getParams().setParameter(“http.protocol.reject-relative-redirect”, false);
//httpClient.getParams().setParameter(“http.protocol.max-redirects”, 2);//http.protocol.max-redirects
httpClient.getParams().setParameter(“http.protocol.expect-continue”, false);//dela
//httpClient.getParams().setParameter(“http.protocol.allow-circular-redirects”, true); //dovolimo redirekte na isto lokacijo
//httpClient.getParams().setParameter(“http.connection.stalecheck”, true); veze

//http.connection.stalecheck

//httpClient.getParams().setBooleanParameter(
// “http.protocol.expect-continue”, false); //tole tud ne pomaga

//Log.i(“parametri”,httpClient.getClass().toString());
//byte[] data = IOUtils.toByteArray(is);
//InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data), “uploadedFile”);

StringBody zadeva = new StringBody(“Mobi”);
StringBody vsebina = new StringBody(“Test”);
StringBody podrocje = new StringBody(“23″);
StringBody skupina = new StringBody(“6″);
//StringBody mail= new StringBody(“luka@car.com”);
//StringBody telefon = new StringBody(“123456789″);
StringBody poslji=new StringBody(“Pošlji”);

MultipartEntity multipartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); //”—————————293582696224464″ ,Charset.forName(“UTF-8″)

multipartContent.addPart(“_ctl8:_ctl1:_ctl0:ddlSkupine”, skupina);
multipartContent.addPart(“_ctl8:_ctl1:_ctl0:ddlPodrocja”, podrocje);
//multipartContent.addPart(“_ctl8:_ctl1:_ctl0:txtEPosta”, mail);
//multipartContent.addPart(“_ctl8:_ctl1:_ctl0:txtTelefon”, telefon);
//multipartContent.addPart(“_ctl8:_ctl1:_ctl0:MultiUpload:File1″, isb);
multipartContent.addPart(“_ctl8:_ctl1:_ctl0:txtZadeva”, zadeva);
multipartContent.addPart(“_ctl8:_ctl1:_ctl0:txtVsebina”, vsebina);
multipartContent.addPart(“_ctl8:_ctl1:_ctl0:cmdPoslji”,poslji); //komanda??

postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);

Log.d(“HTTPKODA”,res.getStatusLine().toString() );

HttpEntity resEntity = res.getEntity();
if (resEntity != null) {
Log.d(“ODGOVOR”,EntityUtils.toString(resEntity));//tole je odgovor
}
httpClient.getConnectionManager().shutdown(); //sprostimo resurse

//res.getEntity().getContent().close(); //ce tole zivo javi napako
} catch (IOException e) {
throw e;
}

}

I also used wireshark to compare http post header that was succesful(via website) and mine from the phone.
There are fewer data in the header in my phone app (accept charset,accept encoding… are missing), so i checked http://hc.apache.org/httpclient-3.x/preference-api.html but couldn’t get the right parameters- maybe the missing parameters are not the cause of the problem.

hope you didn’t get bored by this long post :)

Wow!, please do it one step at a time, your code is too messy to work with, but try to send one parameter at a time to see if it gets through, if you need, build simple php/jsp/whatever website to accept those parameters and see if its working, once you got that, you will shift to your friends website.

It’s workig now, my code was working, the bug was on the server. Your snippets are great, tnx!

Thank’s a lot for this code. Works great for me! I was searching for days for a simple way to send multipart post data. Now found it!

Hello!

Does anyone here know how to set encoding in http get request as described above right to display characters (č,š,ž) in response correctly?

I tried with:
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,
“UTF-8″);
but it’s not working.

Thank you

After getting the response in XML format you can set the Encoding for XML before displaying the data.

Clear simple tutorial . thank you so much

Write a comment