如何检查HTTP请求的响应?

时间:2014-01-03 07:18:46

标签: php android http

我在4个月前完成了一个小型Android项目(MAP和基于位置)。现在我计划通过升级map API和一些代码调整来改进App。作为其中的一部分,我想问一下如何有效地检查来自Web服务器的HTTP请求的响应。我目前的策略是:

  • App会使用 HTTP GET 方法将数据上传到PHP服务器。
  • 服务器的响应将采用XML标记格式。
  • 我必须检查来自服务器的响应的相应标记(使用在Stack Overflow xml解析器中看到的xmlParser示例)。

我认为这对我来说有点烦人。有没有简单的方法来实现这个过程?

例:
如果用户尝试登录,将在SERVER中检查凭证,并且成功的身份验证将作为一些代码回复:1 else:0。

所有HTTP请求都作为asynctask处理。

1 个答案:

答案 0 :(得分:1)

public String login(String login_url,List<NameValuePair> login_parameters_list) throws ClientProtocolException, IOException
{
    int response_code = -1;
    HttpPost httppost = new HttpPost(post_url);
    httppost.setEntity(new UrlEncodedFormEntity(post_parameters_list));
    HttpResponse response = httpclient.execute(httppost);
    // coockie management 
    httpclient.getCookieStore().getCookies().get(0).getName();
    response_code = response.getStatusLine().getStatusCode();

    if(response_code == 999 || response_code == HttpStatus.SC_INTERNAL_SERVER_ERROR)
    {
        Log.e("HttpResponse", "Internal Server");

    }
    else if(response_code == -1 )
    {
        Log.e("HttpResponse", "Socket connection timeout");

    }
    if (response_code == HttpStatus.SC_UNAUTHORIZED)
    {
        // credential check failed
        Log.e("HTTP status", "unauthorised");

    }
    else if (response_code == HttpStatus.SC_FORBIDDEN)
    {
        // forbidden
        Log.e("HTTP status", "Forbidden");

    }
    return response_code == HttpStatus.SC_OK ? EntityUtils.toString(response.getEntity()) : null;
}