使用HttpGet返回完整的HTML代码

noo*_*oob 1 android web-services http-get

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

 http://www.example.com/trip/details/860720?format=json
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

yor*_*rkw 6

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

httpget.setHeader("Accept", "application/json"); // or application/jsonrequest
httpget.setHeader("Content-Type", "application/json");
Run Code Online (Sandbox Code Playgroud)

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

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

int responseStatusCode = response.getStatusLine().getStatusCode();
Run Code Online (Sandbox Code Playgroud)

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

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