我尝试在我的电脑上连接php,但Android代码将停在 public String doInBackground(Void... arg0){
HttpURLConnection con = null;
String urlString = "http://localhost:8081/PHP/Android_SQL.php";
System.out.println("before try");
String res = "";
try {
URL url = new URL(urlString);
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(15000);
con.setConnectTimeout(10000);
con.setRequestMethod("GET");
//set input and output descript
con.setDoInput(true);
con.setDoOutput(false); // in needed?
System.out.println("connecting");
con.connect(); // won't work
System.out.println("connect ");
System.out.println(con.getURL());
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
sb.append(line + "\n");
System.out.println(line);
}
json = sb.toString();
br.close();
return json;
}catch (SocketTimeoutException a){
a.getMessage();
}catch (IOException b){
b.getMessage();
}catch (Exception e) {
e.getMessage();
}
finally {
System.out.println("sueecssful");
}
return null;
}
我不知道它发生了什么。
05-24 20:27:44.032 3089-3089/com.example.user.tophp I/System.out: click the button
05-24 20:27:44.033 3089-3237/com.example.user.tophp I/System.out: before try
05-24 20:27:44.033 1524-1595/system_process W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
05-24 20:27:44.033 3089-3237/com.example.user.tophp I/System.out: connecting
05-24 20:27:44.036 3089-3237/com.example.user.tophp I/System.out: sueecssful
我发现其中一个问题是SSL认证?
logcat:
Vagrant.configure("2") do |config|
config.vm.network "forwarded_port", guest: 2003, host: 12003, protocol: "tcp"
config.vm.network "forwarded_port", guest: 2003, host: 12003, protocol: "udp"
end
答案 0 :(得分:1)
您正在尝试连接到localhost:8081
,而adb
本身就是Android设备。
使用localhost
通过USB向您的计算机移出正向/反向,或者只需将192.168.0.2:8081
替换为本地网络上计算机的IP 即可。示例:catch (SocketTimeoutException a){
a.getMessage();
}catch (IOException b){
b.getMessage();
}catch (Exception e) {
e.getMessage();
}
其他潜在问题:
a.getMessage();
至少将a.printStackTrace()
替换为Log.e("MyTag", "Error", a);
以打印错误。但实际上你应该使用catch (SocketTimeoutException a){
Log.e("MyTag", "Timout Error", a);
}catch (IOException b){
Log.e("MyTag", "IO Error", b);
}catch (Exception e) {
Log.e("MyTag", "Error", e);
}
* https://developer.android.com/reference/android/util/Log.html
<uses-permission android:name="android.permission.INTERNET"/>
另外,请确保在清单{{1}}
中添加了以下内容