我正在创建一个应用程序,我想在互联网(通过2G网络)连接可用时将图像,文本发送到服务器。
我正在使用服务器中的计时器线程来实现这个逻辑,它可以在1分钟后检查互联网连接是否可用。
这里我遇到了这个逻辑的问题:
一个。要将图像发送到它需要1-2分钟(超过2G)。因此,如果用户上传他的图像并且他从一个区域(可以使用互联网连接)移动到其他区域(互联网连接不可用),那么在这种情况下,我无法在上传后获得图像。
那么在上述情况下如何确保图像上传到服务器。
public String uploadFileToServer(String image1,String image2,String image3) {
String result = null;
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 25000);
HttpConnectionParams.setSoTimeout(httpParameters, 25000);
HttpClient httpClient = new DefaultHttpClient();
HttpPost postResquest= new HttpPost(URL);
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
// code for send image using post method
System.out.println("Image1="+image1);
System.out.println("Image2="+image2);
System.out.println("Image3="+image3);
reqEntity.addPart("image1",new FileBody(new File(image1)));
reqEntity.addPart("image2",new FileBody(new File(image2)));
reqEntity.addPart("image3",new FileBody(new File(image3)));
System.out.println("uploaded"+"image added Parameter added");
postResquest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postResquest);
int sucess=response.getStatusLine().getStatusCode();
System.out.println("status code:"+sucess);
if(sucess==200)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null)
{
s = s.append(sResponse);
}
System.out.println("Upload photo Response" + s);
result=s.toString();
}
else
{
HashMap<String, String> hashMap=new HashMap<String, String>();
hashMap.put("flag", "-1");
JSONObject jsonObject =new JSONObject(hashMap);
result=jsonObject.toString();
}
// return getUploadResponce(s.toString());
// Log.i("Response ", );
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
HashMap<String, String> hashMap=new HashMap<String, String>();
hashMap.put("flag", "-1");
JSONObject jsonObject =new JSONObject(hashMap);
result=jsonObject.toString();
}
return result;
} // end of upload file toserver
答案 0 :(得分:0)
如果连接失败,将抛出异常(IOException,TimeoutException等),只需将try {} catch块包围的连接