我需要使用multipart从我的Android上传一个文件并尝试使用以下代码,但没有运气。 我遇到了连接超时异常,尝试使用具有相同结果的不同代码。
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addTextBody(USER_ID, "DFD");
entityBuilder.addTextBody(NAME, "DFD");
String filepath = Environment.getExternalStorageDirectory() + "/Download/myImage.jpg";
Log.d(MULTIPART_TAG, filepath);
File file = new File(filepath);
if(file != null)
{
entityBuilder.addBinaryBody("IMAGE", file);
}
HttpEntity entity = entityBuilder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity);
Log.v("result", result);
}
catch(Exception e)
{
e.printStackTrace();
}
以下是我得到的例外情况:
08-06 17:49:03.006:W / System.err(24761):引起: libcore.io.ErrnoException:connect failed:ETIMEDOUT(连接定时 出)
我也试过这些解决方案:
https://stackoverflow.com/a/19188010/1948785
以及已弃用的课程 MultipartEntity
我的第二个问题是这个警告的含义是什么(我不知道它是否与我的问题有关但我在执行请求时得到了它):
08-06 17:45:53.461:W / dalvikvm(24761):VFY:无法解决静态问题 3008(INSTANCE)in Lorg /阿帕奇/ HTTP /消息/ BasicHeaderValueParser;
我正在使用的lib是:
答案 0 :(得分:0)
试试这个,
DefaultHttpClient httpClient = new DefaultHttpClient();
// yourimagefile is your imagefile
HttpPost httpPostRequest = new HttpPost(URL);
// Try This
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(yourimagefile, "image/jpeg");
mpEntity.addPart("file", cbFile);
httpPostRequest.setEntity(mpEntity);
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
答案 1 :(得分:0)
尝试设置HttpClient的超时持续时间。
int TIMEOUT_MILLISEC = 20000; // = 20 seconds
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
答案 2 :(得分:0)
检查图像的大小。可能是图像太大而上传需要很长时间,服务器在该连接上发出超时。