我正在开发安卓应用程序,它将图像以及一些参数上传到服务器。从我的服务方面,我们使用@RequestParam文件和@RequestParam getProjectsData作为getProjectsData方法中的参数,其中包含存储在数据库中的所有图像详细信息。在这里,当我从我的安卓应用程序上传图像时,我收到一个名为 HTTP Status 400 - Required request part 'getProjectsData' is not present
的错误。后来我知道我需要从我这边发送多个多部分数据。谁能告诉我如何发布多个分段请求,一个用于图像上传,另一个用于图像属性上传这是我的安卓应用代码
AsyncTask<String, Void, String> uploadImageDetails = new AsyncTask<String, Void, String>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
pm_image_details_model pm_img_model = new pm_image_details_model();
pm_img_model.setLatitude(String.valueOf(pm_latitude));
pm_img_model.setLongitude(String.valueOf(pm_longitude));
String result = null;
org.apache.http.entity.mime.MultipartEntity reqEntity = new org.apache.http.entity.mime.MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
// reqEntity.addPart("getProjectsData", new StringBody(""));
bos = new ByteArrayOutputStream();
final Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "test.jpeg");
try {
reqEntity.addPart("file", bab);
reqEntity.addPart("getProjectsData",new StringBody(json));
content = getHttpPutContent(urls[0], reqEntity);
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Result from server -->", s);
}
};
HTTP 客户端
public static String getHttpPutContent(String url, org.apache.http.entity.mime.MultipartEntity multipartEntity) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost put = new HttpPost(url);
// put.setHeader("Content-Type", "multipart/form-data");
// Log.i(TAG, "Token=> " + token);
Log.i("-->", "Try to open=> " + url);
org.apache.http.entity.mime.MultipartEntity reqEntity = multipartEntity;
put.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(put);
int statusCode = httpResponse.getStatusLine().getStatusCode();
Log.i("-->", "Connection code: " + statusCode);
HttpEntity entity = httpResponse.getEntity();
String serverResponse = EntityUtils.toString(entity);
Log.i("-->", "Server response=> " + serverResponse);
if (!isStatusOk(statusCode))
return null;
return serverResponse;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
您可以同时发送文件和数据:
public MultipartUtility() {
}
public static String getContent(HttpResponse response) throws IOException {
System.out.println("response code : " + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String body = "";
String content = "";
while ((body = rd.readLine()) != null) {
content += body + "n";
}
return content.trim();
} else {
if (response.getStatusLine().getStatusCode() == 401) {
return Constants.UnAuthorized;
} else {
return "Error";
}
}
}
// here fileName means path of file.
public String postFile(String fileName, String body) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Your Api is here);
HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 30000);
HttpConnectionParams.setSoTimeout(params, 30000);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
if (fileName != null) {
final File file = new File(fileName);
FileBody fb = new FileBody(file);
builder.addPart("file", fb);
builder.addPart("photoCaption", new StringBody(body));
}
final HttpEntity yourEntity = builder.build();
class ProgressiveEntity implements HttpEntity {
@Override
public void consumeContent() throws IOException {
yourEntity.consumeContent();
}
@Override
public InputStream getContent() throws IOException,
IllegalStateException {
return yourEntity.getContent();
}
@Override
public Header getContentEncoding() {
return yourEntity.getContentEncoding();
}
@Override
public long getContentLength() {
return yourEntity.getContentLength();
}
@Override
public Header getContentType() {
return yourEntity.getContentType();
}
@Override
public boolean isChunked() {
return yourEntity.isChunked();
}
@Override
public boolean isRepeatable() {
return yourEntity.isRepeatable();
}
@Override
public boolean isStreaming() {
return yourEntity.isStreaming();
} // CONSIDER put a _real_ delegator into here!
@Override
public void writeTo(OutputStream outstream) throws IOException {
class ProxyOutputStream extends FilterOutputStream {
/**
* @author Stephen Colebourne
*/
public ProxyOutputStream(OutputStream proxy) {
super(proxy);
}
public void write(int idx) throws IOException {
out.write(idx);
}
public void write(byte[] bts) throws IOException {
out.write(bts);
}
public void write(byte[] bts, int st, int end) throws IOException {
out.write(bts, st, end);
}
public void flush() throws IOException {
out.flush();
}
public void close() throws IOException {
out.close();
}
} // CONSIDER import this class (and risk more Jar File Hell)
class ProgressiveOutputStream extends ProxyOutputStream {
public ProgressiveOutputStream(OutputStream proxy) {
super(proxy);
}
public void write(byte[] bts, int st, int end) throws IOException {
// FIXME Put your progress bar stuff here!
out.write(bts, st, end);
}
}
yourEntity.writeTo(new ProgressiveOutputStream(outstream));
}
}
;
ProgressiveEntity myEntity = new ProgressiveEntity();
post.setEntity(myEntity);
HttpResponse response = client.execute(post);
return getContent(response);
}
}
像下面这样调用这个类:
new MultipartUtility().postFile(filepath, body);
在此处传递文件路径并将参数作为主体传递。