我正在尝试开发一个Android应用程序,它调用一个php文件来查询和从数据库中提取数据。该URL可以通过Web浏览器在我的手机上访问,但我似乎无法通过下面的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
方法,因为它更安全。
答案 0 :(得分:2)
如果是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;
}`
答案 1 :(得分:1)
请确保Manifest和WIFI中的以下两行已启用并连接到子网10.0.3.x
var str = getDataValue();
//str value is in this format = "aVal,bVal,cVal,dVal,eVal"
如果获得post方法,那么“?”在你的网址?
答案 2 :(得分:0)
您可以使用此方法ByteArrayOutputStream
同样这个我用于我的一个项目cluesshop.com