Dangerbunny Dangerbunny - 2 months ago 20
Java Question

How to create a org.apache.http.entity.mime.content.FileBody when using Google App Engine

So I'm trying to make a multipart-form POST and I want to attach a

org.apache.http.entity.mime.content.FileBody
to the
MultipartEntity
that I'm going to be posting. Now I've got the raw string file data that I want to populate the
FileBody
with already. However, this project is using Google App Engine which prohibits every way I've seen of generating the FileBody. Anyone know how to create a
FileBody
object and populate it in GAE?

Answer

So just ignore FileBody. You want to use the method MultipartEntity.addPart(ContentBody content). This works with FileBody, because FileBody's parent class implements ContentBody.

ContentBody is a super simple interface with just two methods. Create a class that implements it, create an instance of your class, and pass it in to the addPart method.

public ByteContentBody implements ContentBody {
  private String name;
  private byte[] data;

  public ByteContentBody(String name, byte[] data) {
    this.name = name;
    this.data = data;
  }

  public String getFilename(){
    returns name;
  }

  public void writeTo(OutputStream out) throws IOException {
    out.write(data);
  }
}

http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntity.html

http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/content/ContentBody.html

Comments