• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Uploading File using HTTP Post

redbrad0

Lurker
Aug 31, 2011
5
0
I found this script and have altered it to fit my needs, but now I need to upload a file with the form fields. I have found examples but I cant seem to get it to work. Can someone help on what I would need to do.

Code:
    public static String send_HTTPPost(String url, String data, String contentType) {
        String result = null;
        
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

        HttpPost httpPost = new HttpPost(url);
        HttpResponse response = null;
        HttpContext localContext = new BasicHttpContext();
        StringEntity tmp = null;        

        httpPost.setHeader("User-Agent", "MyApp Version:" + GlobalSettings.applicationVersionNumber);
        httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

        if (contentType != null) {
            httpPost.setHeader("Content-Type", contentType);
        } else {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        }

        try {
            tmp = new StringEntity(data,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO: HOW TO HANDLE THE ERROR
        }

        httpPost.setEntity(tmp);

        try {
            response = httpClient.execute(httpPost,localContext);

            if (response != null) {
                result = EntityUtils.toString(response.getEntity());
            }
        } catch (Exception e) {
            // TODO: WHAT TO DO WITH ERROR
        }

        return result;
    }
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones