我已经将一些.php文件上传到我的服务器,该服务器使用cPanel连接到存储在同一服务器上的MySQL数据库。这些文件位于 public_html/myfiles 上。然后我猜我的文件URL将是"www.myserver.com/myfiles/file2.php"
我正在尝试使用以下代码确定我的 Android 应用程序是否可以找到它:
public boolean exists(String URLName){
try {
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setFollowRedirects(false);
con.setInstanceFollowRedirects(false);
con.setRequestMethod("HEAD");
con.setDoOutput(false);
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
URLName = "www.myserver.com/myfiles/file2.php"
此方法返回 false。
我还尝试使用以下代码使用 Volley:
private void getData() {
String id = "1";
if (id.equals("")) {
Toast.makeText(getContext(), "Please enter an id", Toast.LENGTH_LONG).show();
return;
}
String url = "www.myserver.com/myfiles/file2.php?id="+id;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
Log.d("VOLLEY RESPONSE",s);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("VOLLEY ERROR","Error");
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
但是我得到一个凌空错误,它没有提供太多信息..它只返回 500"服务器错误"。
我该怎么做?还是我做错了什么?
您可以在凌空抽射的情况下尝试这样做:
URL = String.format("http://www.example.com/test/?val_1=%1$s&val_2=%2$s",first,second);
使用 JsonObjectRequest alogn 与这个 url....
final String url = "http://httpbin.org/get?param1=hello";
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
// display response
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", response);
}
});
queue.add(getRequest);
也看看这个
问题解决了。
这是这些文件上的.php代码的问题(我没有写"?>"来关闭文件),与Android Java编码无关。它与JsonObjectRequest和StringRequest一起工作得很好。
我遇到了同样的问题,并对php
和java
代码都使用了GET
,然后按预期得到了响应。
StringRequest strObjRequest = new StringRequest(Request.Method.GET,
"http://www.mpworld.in/test.php?name="+trainNumber+"&email="+date+"&question="+date,
listener, errorListener)