Addev
Addev

Reputation: 32233

Post a file (and more values) into a http request in java

This is my code for making a HTTP post to an url

public static String post(String url, List<BasicNameValuePair> postvalues) {
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        if ( (postvalues==null) ){
            postvalues= new ArrayList<BasicNameValuePair>();
        } 
        httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        return requestToString(response);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

I'd like to add also a file to the post (not a byte[] with the final, just post the file into the PHP $_FILES field.

How can I do it?

Thanks

Upvotes: 1

Views: 771

Answers (1)

Perception
Perception

Reputation: 80603

Sounds like you want to send a multi part request. This assumes that you can handle such a request on the server side:

HttpParams params = new BasicHttpParams();
for(BasicNameValuePair postValue: postValues) {
    params.setParameter(postValue.getName(), postValue.getValue());
}

HttpPost post = new HttpPost();
post.setParams(params);

MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(new File(myFile)));
post.setEntity(entity);

Alternatively to sending the name-value pairs as parameters, you can create a UrlEncodedFormEntity entity just like you are now, and add it to the multipart entity, as a separate part.

Upvotes: 3

Related Questions