mysanders
mysanders

Reputation: 3

Java HttpPost to a php API

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?

Upvotes: 0

Views: 1332

Answers (1)

vbence
vbence

Reputation: 20343

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.

Upvotes: 1

Related Questions