在我的应用程序中,我一直使用DefaultHttpClient
将图像上传到服务器,但是在服务器关闭时需要花费太多时间来做出响应。我把我的代码放在这里。并且AFIK DefaultHttpClient
将被弃用,因此我想使用OkHttp
代替DefaultHttpClient
。所以请帮我改变我的代码,使用OkHttp
上传图片。我搜索了很多,但不知道如何进行更改。请帮帮我....
public String upLoadImg(byte[] image,String name,String phone,String imei,String randomId){
String mResponseData = null;
try{
mHttpClient = new DefaultHttpClient();
mHttpPost = new HttpPost(Constants.BASE_URL +"user/asset");
mHttpPost.setHeader("Accept", "application/json");
mHttpPost.setHeader("mobile-number", phone);
mHttpPost.setHeader("uid", imei);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
if(image !=null) {
ByteArrayBody bab = new ByteArrayBody(image, name);
reqEntity.addPart("file", bab);
}
mHttpPost.setEntity(reqEntity);
Log.e("TAG", "***** mHttpClient is going to execute ");
HttpParams httpParameters = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 2 * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 2 * 1000);
mHttpResponse = mHttpClient.execute(mHttpPost);
HttpEntity resEntity = null;
if(mHttpResponse!=null)
resEntity = mHttpResponse.getEntity();
if(resEntity!=null)
mResponseData = EntityUtils.toString(resEntity).trim();
}catch(HttpHostConnectException e){
Log.e("TAG","Exception cannot connect to server while sending images ",e);
return null;
}catch(Exception e){
Log.e("TAG","Exception occured while sending images ",e);
return null;
}
return mResponseData;
}
答案 0 :(得分:0)
我通过用Okhttpclient替换DefaultHttpClient克服了这个问题。 据我所知,DefaultHttpClient在最新的android版本中已被弃用。所以我已经切换到OkHttpClient然后修复了所有问题