首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android -通过HTTPClient连接HTTPClient

Android -通过HTTPClient连接HTTPClient
EN

Stack Overflow用户
提问于 2013-05-22 17:29:18
回答 1查看 733关注 0票数 0

我正在尝试在我的新应用程序中创建一个登录功能。我在服务器中编写了一个php文件,作为我的应用程序和MySQL之间的接口。

JAVA代码

代码语言:javascript
复制
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代码//为了提高可读性,我删除了不相关的代码,并简化了剩下的代码,目的是展示我将要做的事情。

代码语言:javascript
复制
<?php
        if ($_POST['username'] == 'user' && $_POST['password'] == 'pw')
                echo 'Success';
        else
                echo 'Failed';
?>

我预计responseMessage将等于“成功”,但结果是它返回一个空值。

  1. 我会在web浏览器中尝试php文件,它正常工作,我确信问题来自JAVA代码。
  2. 我尝试使用response.getStatusLine().getStatusCode()方法检查HTTP代码,但它不返回任何数字。

请帮帮忙!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-22 19:30:48

尝试将String responseMessage = response.getEntity().toString();行替换为java代码中的以下行:

代码语言:javascript
复制
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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16698108

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档