我正在尝试开发一个 Android 应用程序,它调用 php 文件来查询并从数据库中提取数据。该 URL 可以在我的手机上通过网络浏览器访问,但我似乎无法从下面的 java 代码中调用它。任何人都可以帮助我从我的 Java 代码调用我的 PHP 文件。
URL url = new URL("http://10.0.3.2/MYCODE/app/login.php");
String urlParams = "name="+name+"&password="+password;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
我收到以下错误:java.io.FileNotFoundException:
我正在使用POST
方法,因为它更安全。
如果是 GET 方法,那么我们可以使用以下代码行,您的调用文件的问题可能是您的 .php 文件路径不正确
//Integrating url with values [Starts]
Map<String, String> request = new HashMap<String, String>();
request.put("name", name);
request.put("password", password);
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.encodedPath("http://10.0.3.2/MYCODE/app/login.php");
if (mapOfStrings != null) {
for (Map.Entry<String, String> entry : request.entrySet()) {
Log.d("buildSanitizedRequest", "key: " + entry.getKey()
+ " value: " + entry.getValue());
uriBuilder.appendQueryParameter(entry.getKey(),
entry.getValue());
}
}
String uriString;
try {
uriString = uriBuilder.build().toString(); // May throw an
// UnsupportedOperationException
} catch (Exception e) {
Log.e("Exception", "Exception" + e);
}
//Integrating url with values [Ends]
HttpURLConnection connection = null;
try {
URL url = new URLuriBuilder.build().toString());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Accept-Charset", "utf-8,*");
Log.d("Get-Request", url.toString());
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
Log.d("Get-Response", stringBuilder.toString());
return new JSONObject(stringBuilder.toString());
} finally {
connection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}`
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)