我开发了一个小型的Android应用程序,它通过Http协议与服务器通信,使用json对象。
它在我的本地机器上工作得很好,但是当我决定(仅仅是为了学习目的)将我的php脚本上传到一些免费托管网络服务时,我得到了406 ERROR。
我做了一些研究,发现必须在我的HttpPost请求中没有设置Content-type。但是设置Content-type并没有帮助。
这是android代码:
ArrayList<NameValuePair> userData = new ArrayList<NameValuePair>();
userData.add(new BasicNameValuePair("email", userData_email));
userData.add(new BasicNameValuePair("pass", userData_pass));
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost(uri);
// I tried this too
// postRequest.setHeader("Content-Type", "application/json");
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(userData);
ent.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
postRequest.setEntity(ent);
HttpResponse response = client.execute(postRequest);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Log.e("SERVER: ", result);
JSONObject json = new JSONObject(result);
userData_fname = json.getString("fname");
userData_lname = json.getString("lname");
userData_age = json.getInt("age");
userData_gender = json.getString("gender");
这是来自服务器的代码(真的没什么特别的):
$mysql_host = 'xxxx';
$mysql_user = 'xxxx';
$mysql_pass = 'xxxx';
$mysql_db = 'xxxx';
if (isset($_POST["email"]) && isset($_POST["pass"])) {
$email = $_POST["email"];
$pass = $_POST["pass"];
if(!mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !mysql_select_db($mysql_db)) {
echo '-1';
}
$query = "SELECT * FROM `users` WHERE `email`='".$email."' AND `password`='".$pass."'";
if($query_run = mysql_query($query)){
$firstname = mysql_result($query_run, 0, 'firstname');
$lastname = mysql_result($query_run, 0, 'lastname');
$age = mysql_result($query_run, 0, 'age');
$gender = mysql_result($query_run, 0, 'gender');
$return_data = array (
'fname' => $firstname,
'lname' => $lastname,
'age' => $age,
'gender' => $gender
);
echo json_encode($return_data);
} else {
echo 'not found';
exit();
}
}
现在,它可能是我的PHP代码(可能缺少一些东西),但因为我只知道php的基础知识我要求你的帮助。
提前谢谢。
答案 0 :(得分:1)
你改变了:
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);`
HttpClient client = new DefaultHttpClient(httpParameters);
致:
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),
timeOut);
HttpConnectionParams.setSoTimeout(httpclient.getParams(), timeOut);`
当然,它有效。
答案 1 :(得分:0)
如果您想确定您的PHP代码,您必须从浏览器打开该页面,如果您将以JSON格式看到您的数据,那么服务器工作正常!否则,您的服务器不会检索json_encode()
功能。