开发者

Unable to handle responses timeout using HTTPURLConnection in android

开发者 https://www.devze.com 2023-04-12 03:31 出处:网络
I use the following code to upload a file to server, it seems to working fine,when i got uploaded and get back some responses form data, but when connection time out or lose my conn开发者_运维问答ecti

I use the following code to upload a file to server, it seems to working fine,when i got uploaded and get back some responses form data, but when connection time out or lose my conn开发者_运维问答ectivity i didnt get any responses and the execution of function stop, still wait for responses from server , i dont know how to handle the connection timeout problem even i set

conn.setTimeout(2000);

but it seems not working with HTTPUrlConnection, any body help me out to sort this problem.

private String uploadVideo(String path,String videoDuration) {
    // TODO Auto-generated method stub
    String line=null;
    String status="false";



     String upLoadServerUri ="serverURL";
     String fileName = path;

      HttpURLConnection conn = null;
      DataOutputStream dos = null;
      String lineEnd = "\r\n";
      String twoHyphens = "--";
      String boundary = "*****";
      int bytesAvailable; 
      byte[] buffer;
      int maxBufferSize = 1 * 1024 * 1024;
      File sourceFile = new File(path);

      if (!sourceFile.isFile()) {
       Log.e("Huzza", "Source File Does not exist");
       status="File not exist";
      }
      int serverResponseCode=0;
    try {

        // open a URL connection to the Servlet
       FileInputStream fileInputStream = new FileInputStream(sourceFile);
       URL url = new URL(upLoadServerUri);
       conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
       conn.setDoInput(true); // Allow Inputs
       conn.setDoOutput(true); // Allow Outputs
       conn.setUseCaches(false); // Don't use a Cached Copy
       conn.setRequestMethod("POST");
       conn.setConnectTimeout(3000);

       conn.setRequestProperty("Connection", "Keep-Alive");
       conn.setRequestProperty("ENCTYPE", "multipart/form-data");
       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
       conn.setRequestProperty("uploadedfile", fileName);

       conn.setRequestProperty("duration",videoDuration);
       dos = new DataOutputStream(conn.getOutputStream());

       dos.writeBytes(twoHyphens + boundary + lineEnd);
       dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""+ fileName + "\"" + lineEnd);
       dos.writeBytes(lineEnd);

       bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size
       Log.i("Huzza", "Initial .available : " + bytesAvailable);


       buffer = new byte[1024];
       int len;
       int state=0;
       while((len=fileInputStream.read(buffer))>0){
           state=state+len;
           dos.write(buffer);

       }

       dos.writeBytes(lineEnd);
       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

       // Responses from the server (code and message)
       serverResponseCode = conn.getResponseCode();
       String serverResponseMessage = conn.getResponseMessage();

       Log.i("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
       // close streams
       Log.i("Upload file to server", fileName + " File is written");
       fileInputStream.close();
       dos.flush();
       dos.close();

       try {
           BufferedReader rd = new BufferedReader(new InputStreamReader(conn
             .getInputStream()));

           while ((line = rd.readLine()) != null) {
            Log.i("Huzza", "RES Message: " + line);
            System.out.println("RES:"+line);
            status=line;
           }
           rd.close();
          } catch (IOException ioex) {
           Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
           status="false";
          }  

      }

    catch (SocketException e){
        status="false";
           System.out.println("Socket Exception occured");
    }
    catch (MalformedURLException ex) {
       ex.printStackTrace();
       status="false";
       Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
      }
    catch(SocketTimeoutException e){
        e.printStackTrace();
        status="false";

    }
      catch(ConnectTimeoutException e){
          status="false";
          Log.e("Upload file to server", "error: " + e.getMessage(), e);
      }
      catch (Exception e) {
          e.printStackTrace();
       System.out.println("Err:");
       status="false";
      }

    //this block will give the response of upload link


    return status;


}

That Catch connectionTimeout block won`t execute at all.


Try this way Just add these two lines and check it once.

 conn.setConnectTimeout(TIMEOUT_LIMIT);
 conn.setReadTimeout(TIMEOUT_LIMIT);
0

精彩评论

暂无评论...
验证码 换一张
取 消