Skip to content

Instantly share code, notes, and snippets.

@moltak
Created December 28, 2013 12:55
Show Gist options
  • Select an option

  • Save moltak/8159238 to your computer and use it in GitHub Desktop.

Select an option

Save moltak/8159238 to your computer and use it in GitHub Desktop.
멀티파트
package com.startuphouse.wallposter.network;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.startuphouse.wallposter.network.listener.UploadListener;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by moltak on 12/28/13.
*/
public class MultipartRequest extends Request<String> {
private final String PARAM_TITLE = "title", PARAM_CONTENT = "content";
private final String PARAM_UPFILE[] = {"upfile", "upfile2", "upfile3", "upfile4"};
private HttpEntity httpEntity;
private String title, contents;
private ArrayList<String> images;
private Response.Listener<String> listener;
public MultipartRequest(String title, String contents, ArrayList<String> images, String url, UploadListener listener) {
super(Method.POST, url, listener);
this.title = title;
this.contents = contents;
this.images = images;
this.listener = listener;
buildMultipartEntity();
}
private void buildMultipartEntity() {
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.addTextBody(PARAM_TITLE, title,
ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"));
entityBuilder.addTextBody(PARAM_CONTENT, contents,
ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"));
for(int i = 0; i < images.size(); i ++) {
entityBuilder.addPart(PARAM_UPFILE[i], new FileBody(new File(images.get(i))));
}
httpEntity = entityBuilder.build();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
return Response.success(new String(response.data), getCacheEntry());
}
@Override
protected void deliverResponse(String response) {
listener.onResponse(response);
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpEntity.writeTo(bos);
}
catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
public String getBodyContentType() {
String contentType = httpEntity.getContentType().getValue();
return contentType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment