0

Im trying to upload a file to a site using their API trough java on android.

This is what im using to post and get a response:

    public static HttpResponse upload(String imagePath){
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("www.site.com/api.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("type", "file"));
        nameValuePairs.add(new BasicNameValuePair("image", "@" + imagePath));
        nameValuePairs.add(new BasicNameValuePair("thumbsize", "200"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        System.out.println("tryar");
        System.out.println(EntityUtils.toString(httppost.getEntity()));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost); 
        return response;

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;

}

The response is a xml file witch i read and that part seems to work. The response i get is "No file uploaded!".

The site have an example on how to call the api from php curl:

      // post with curl

   $ch = curl_init($postURL);

   $post['type']='file';
   $post['image']='@'.$filename;

   // You can set this to either 100,200,300, or 400 to specify the size of the thumbnail
   $post['thumbsize']="400";   

   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_HEADER, false);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_TIMEOUT, 240);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: '));

   $result = curl_exec($ch);
   curl_close($ch);

   return $result;

http://www.glowfoto.com/api_upload.php

I have a very limited knowledge of webprogramming but isn't this equivalent to what im doing in java?

1 Answer 1

1

You have to post the file, not just a filename with a @ sign. Curl has a form emulation capability which defines that variables starting with @ mean file uploads, but that is strictly a cURL function. Do not expect the same behavior from Android API.

Yocan use File and MultipartEntity. This question has a nice example code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.