【发布时间】:2014-08-03 12:17:11
【问题描述】:
我有一个应用程序需要将许多拍摄的照片上传到服务器。我尝试了很多代码,上面是我最后一次使用的代码。我在 AsyncTask 后面使用它。当我尝试发送文件时,我收到“不支持的媒体类型”415 HTTP 错误。我使用 Chrome 扩展程序 postman 做了一些测试,我可以看到标题是如何制作的:
Content-Disposition: form-data; name="ssss"; filename="beatles-1600x1200.jpg"
Content-Type: image/jpeg
但我看不到这段代码的最终标题。这是我的第二个安卓应用。我的知识贫乏使得解决这种情况变得非常困难。非常欢迎任何帮助!
public String sendOneFile(String url, String fileName)
{
String responseBody = "";
File file = new File(fileName);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("image/jpeg"); //("binary/octet-stream");
reqEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));
reqEntity.setChunked(true);
HttpResponse response = httpclient.execute(httppost);
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
break;
case 415:
return "(Com ERRO) Media type not supported.";
}
//Do something with response...
return responseBody;
} catch (Exception e) {
return "(Com ERRO) " + e.getMessage();
}
}
【问题讨论】:
标签: android file http post upload