2016-07-08 2 views
3

Android가 SDK에서 6.0 이후 Apache 웹 클라이언트를 제거했기 때문에 apk에 라이브러리를 포함하지 않으려 고하므로 HttpURLConnection 메소드로 마이그레이션하고 있습니다. 물건을 테스트하려면URL.openConnection()이 즉시 연결됩니다.

, 나는 대략 다음과 같이 내 데이터베이스에 로그 항목을 추가 아무것도하지 않습니다하지만 내 로컬 서버에 testPost.php을 만들어 :

<?php 
    require_once(__DIR__ . '/db_interface.php'); 
    $conn = connectToDatabase(); 
    $stmt = $conn->prepare('insert into logs(data) values (?)'); 
    $stmt->bind_param(1, $_POST['data']); 
    $stmt->execute(); 
    $stmt->close(); 

을 그리고 난 내 옛날에 있음을 액세스 할 때 웹 클라이언트는 잘 작동합니다. PC의 웹 브라우저도 마찬가지입니다. 나는이 안드로이드 코드하려고 할 때

이제

는 :

 HttpURLConnection connection = null; 
     try { 
      URL url = new URL("http://192.168.2.221/testPost.php"); 

      connection = (HttpURLConnection) url.openConnection(); 
      //As soon as the debugger steps over the above line, the 
      //PHP script executes. 

      //Line below throws IllegalStateException: Already Connected 
      connection.setDoOutput(true); 

      ... 
     } finally { 
      if (connection != null) connection.disconnect(); 
     } 

을가 최대한 빨리 연결을 엽니로 연결하는 것처럼 나는 예외를 얻을. 디버깅 후 url.openConnection() 이상의 단계를 수행하자마자 스크립트가 실행되고 로그 항목이 데이터베이스에 저장됩니다 (emptry 문자열 포함).

내 서버에 데이터를 POST로되어 전체 안드로이드 코드 : 나는 안드로이드 6.0.1

추가를 실행하는 삼성 갤럭시 S7에서 테스트하고 있습니다

 HttpURLConnection connection = null; 
     try { 
      URL url = new URL("http://192.168.2.221/testPost.php"); 

      connection = (HttpURLConnection) url.openConnection(); 
      connection.setDoOutput(true); //throws IllegalStateException: Already Connected 


      if (timeout > 0) { 
       connection.setReadTimeout(timeout * 1000); 
       connection.setConnectTimeout(timeout * 1000); 
      } 

      String postString = writePostParams(params); 
      byte[] postData = postString.getBytes("UTF-8"); 
      connection.setFixedLengthStreamingMode(postData.length); 

      OutputStream out = new BufferedOutputStream(connection.getOutputStream()); 
      out.write(postData); 
      out.flush(); 
      out.close(); 

      InputStream in = new BufferedInputStream(connection.getInputStream()); 
      String response = Util.readInputStream(in); 

     } catch (Exception ex) { 
      Debug.log(ex); 
     } finally { 
      if (connection != null) connection.disconnect(); 
     } 

: 또한 에뮬레이터에 시도 안드로이드 5.0.2, 동일한 결과를 실행합니다.

예외 스택 트레이스는 :

07-08 10:39:30.141 23498-23875/? W/System.err: java.lang.IllegalStateException: Already connected 
07-08 10:39:30.141 23498-23875/? W/System.err:  at java.net.URLConnection.checkNotConnected(URLConnection.java:463) 
07-08 10:39:30.141 23498-23875/? W/System.err:  at java.net.URLConnection.setDoOutput(URLConnection.java:877) 
07-08 10:39:30.141 23498-23875/? W/System.err:  at com.package.from.my.app.executeURL(Server.java:1195) (the line where setDoOutput() is) 

이 내가했던 바보 같은 짓의 명예의 전당 내 개인 홀에 갈 수도
를 해결했다. 디버거에 시계가 connection.getResponseMessage()으로 설정되어 있고 openConnection() 라인을 밟으면 평가되고 연결이 끊어졌습니다.

노력해 주셔서 감사합니다. 다른 사람이 디버깅 시간을 절약 해 주시길 바랍니다.

+0

예외 로그를 ​​게시 할 수 있습니까 –

+0

@ VivekMishra가 추가되었습니다. –

+0

http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests. 열린 연결이 제대로 구현되었는지 확인하려면이 링크를 확인하십시오. 또한'doInput'은 요청 유형을 암시 적으로 게시하도록 설정합니다. 필요하지 않으면 해당 줄을 지울 수 있습니다. –

답변

0

실제로 코드는 괜찮습니다. 아래 링크에서 '게시 내용'을 검색 한 것과 같은 방식으로 구현되었지만 누락 된 사항 만 데이터를 보내려는 방식입니다. 그들은 청크를 사용하고 있습니다. urlConnection.setChunkedStreamingMode (0);
https://developer.android.com/reference/java/net/HttpURLConnection.html 내 서버로 해당 메소드를 테스트하고 체크를 똑같은 결과를 얻을 수있게하십시오.

는이 코드를 테스트의 작업을 잘 난 가지가 일부 서버 보안 문제가 수도 아이디어를 제공하는 예외

public void testURL() { 

     HttpURLConnection urlConnection = null; 
     try { 
      URL url = new URL("http://www.android.com/"); 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setDoOutput(true); 
      urlConnection.setChunkedStreamingMode(0); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      urlConnection.disconnect(); 
     } 
    } 

을 받고 있지 않다.

+0

흥미로운 점은, 같은 예외 인'https : // posttestserver.com/post.php'에도 내 데이터를 POST하려고했습니다. 청크 분할 모드로 시도해 볼 수는 있지만 예외가 발생하기 전에 코드가 그 라인에 도달하지 못하기 때문에 아무런 차이가 보이지 않습니다. –

+0

내가 볼 수있는 다른 에뮬레이터 인스턴스에서 실행하려고합니다. 나에게 장치 사양을 보낼 수 있습니다. –

+0

노력해 주셔서 감사합니다.하지만 OP 편집을 참조하십시오. –