在我的项目中,我需要调用一个URL。
此网址如下:http://myip:80/increaseCounter.php
我有一个带有mysql的Xampp(MAC)。 increaseCounter.php的功能是从表中反转的值,将其增加为1,然后更新它。 我在localhost中测试的网址,通过Chrome从另一台设备指向,并且工作正常。
但是我知道我正试图在Android中调用此链接,我不需要恢复任何数据或类似数据,只需要调用它。
我试着这样做:
private void trackUrl(String href) {
HttpURLConnection con = null;
try {
URL url = new URL(href);
con = (HttpURLConnection) url.openConnection();
con.connect();
} catch (Exception e) {
Log.d("APP", e.getMessage());
} finally {
if (con != null) {
con.disconnect();
}
}
}
但是没有工作。在xampp中没有连接日志,而且mysql中的数据没有更新。
=======
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="my.aswsome.app"
android:versionCode="15">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
.....
答案 0 :(得分:1)
尝试
int code = urlConnection.getResponseCode();
if(code==200){
Log.i("TAG","success");
}
而不是con.connect();
https://developer.android.com/reference/java/net/URLConnection.html#connect()
.connect();
仅打开连接,但之后不执行任何操作。因此,通过.getResponseCode()
实际执行请求。
答案 1 :(得分:0)
you can put url directly that type
URL url = new URL("http://myip:80/increaseCounter.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}