【问题标题】:Using HttpGet returning complete HTML code使用 HttpGet 返回完整的 HTML 代码
【发布时间】:2012-03-21 13:10:24
【问题描述】:

我正在尝试调用一个私有网络服务,其中有一个我必须使用GET 方法访问的链接。在浏览器上使用直接 URL(需要先登录)时,我以 JSON 格式获取数据。我调用的 URL 是这样的

 http://www.example.com/trip/details/860720?format=json

url 工作正常,但是当我使用HttpGet 调用它时,我得到的是网页的 HTML 编码,而不是 JSON 字符串。我使用的代码如下:

private String runURL(String src,int id) {   //src="http://www.example.com/trip/details/"
    HttpClient httpclient = new DefaultHttpClient();   
    HttpGet httpget = new HttpGet(src); 
    String responseBody="";
        BasicHttpParams params=new BasicHttpParams();
        params.setParameter("domain", token); //The access token I am getting after the Login
        params.setParameter("format", "json");
        params.setParameter("id", id);
        try {
                httpget.setParams(params);
                HttpResponse response = httpclient.execute(httpget);
                responseBody = EntityUtils.toString(response.getEntity());
                Log.d("runURL", "response " + responseBody); //prints the complete HTML code of the web-page
            } catch (Exception e) {
                e.printStackTrace();
        } 
        return responseBody;
}

你能告诉我我在这里做错了什么吗??

【问题讨论】:

  • 如果您尝试使用浏览器或 curl 访问该 url,内容是什么
  • 它是一个 json 字符串,如果我尝试通过浏览器调用它,它也应该在 Android 上。

标签: android web-services http-get


【解决方案1】:

尝试在您的 http 标头中指定 Accept & Content-Type:

httpget.setHeader("Accept", "application/json"); // or application/jsonrequest
httpget.setHeader("Content-Type", "application/json");

请注意,您可以使用wireshark 之类的工具捕获和分析收入和结果http 包,并找出从标准浏览器返回您的json 响应的http 标头的确切样式。

更新:
您提到使用浏览器时需要先登录,返回的html内容可能是登录页面(如果使用基本身份验证类型,它会返回一个状态码为401的简短html响应,所以现代浏览器知道如何处理,更具体地说,弹出登录提示给用户),所以第一次尝试是检查你的 http 响应的状态代码:

int responseStatusCode = response.getStatusLine().getStatusCode();

根据您使用的身份验证类型,您可能还需要在 http 请求中指定登录凭据,类似这样(如果是基本身份验证):

httpClient.getCredentialsProvider().setCredentials(
  new AuthScope("http://www.example.com/trip/details/860720?format=json", 80), 
  new UsernamePasswordCredentials("username", "password");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 2017-02-23
    • 2013-05-11
    • 2017-06-02
    • 2021-12-15
    • 1970-01-01
    • 2011-09-16
    相关资源
    最近更新 更多