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()
라인을 밟으면 평가되고 연결이 끊어졌습니다.
노력해 주셔서 감사합니다. 다른 사람이 디버깅 시간을 절약 해 주시길 바랍니다.
예외 로그를 게시 할 수 있습니까 –
@ VivekMishra가 추가되었습니다. –
http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests. 열린 연결이 제대로 구현되었는지 확인하려면이 링크를 확인하십시오. 또한'doInput'은 요청 유형을 암시 적으로 게시하도록 설정합니다. 필요하지 않으면 해당 줄을 지울 수 있습니다. –