其他分享
首页 > 其他分享> > android-使用HttpGet返回完整的HTML代码

android-使用HttpGet返回完整的HTML代码

作者:互联网

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

 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;
}

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

解决方法:

尝试指定“接受并添加” http标头中的Content-Type:

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

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

更新:
您提到使用浏览器时首先需要登录,返回的html内容可能是登录页面(如果使用基本身份验证类型,则返回简短的html响应,其状态码为401,因此现代浏览器知道如何处理,更具体地说,弹出登录提示给用户),因此首先尝试检查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");

标签:http-get,android,web-services
来源: https://codeday.me/bug/20191009/1880347.html