我试图在我的新应用中创建登录功能。 我在我的服务器上写了一个php文件,作为我的App和MySQL之间的接口。
JAVA代码
private void connectPHP(){
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://www.abc.com/login.php"); // I hide the actual URL for security reason.
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("username", "user"));
parameters.add(new BasicNameValuePair("password", "pw"));
request.setEntity(new UrlEncodedFormEntity(parameters, "UTF_8"));
HttpResponse response = client.execute(request);
String responseMessage = response.getEntity().toString();
} catch (Exception e) {}
}
PHP代码//为了提高可读性,我删除了不相关的代码并简化了剩余代码,旨在展示我将要做的事情。
<?php
if ($_POST['username'] == 'user' && $_POST['password'] == 'pw')
echo 'Success';
else
echo 'Failed';
?>
我希望responseMessage等于&#34; Success&#34;,但结果会返回NULL值。
请帮忙!
答案 0 :(得分:0)
尝试用java代码中的这些行替换行String responseMessage = response.getEntity().toString();
:
inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
String responseMessage = sb.toString();