2012-03-21 150 views
1

我想調用一個私人的網絡服務,其中有一個鏈接,我有訪問使用GET方法。在瀏覽器上使用直接URL(需要先登錄)時,我會以JSON格式獲取數據。我調用的URL是這樣的使用HttpGet返回完整的HTML代碼

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

URL是工作正常,但是當我調用此使用HttpGet,我得到的,而不是JSON字符串的網頁的HTML代碼。我使用的代碼如下:

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

你能告訴我我在做什麼錯嗎?

+0

,如果你嘗試用瀏覽器訪問的網址或捲曲 – Blackbelt 2012-03-21 13:15:33

+0

這是一個JSON字符串,如果我嘗試通過瀏覽器來調用它,這是它應該是什麼在Android上也有什麼內容。 – noob 2012-03-21 13:23:34

回答

6

嘗試指定您接受&的Content-Type HTTP頭:

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

注意,您可以使用工具,如wireshark捕獲和分析收入和成果HTTP包,並找出了HTTP的確切風格標題返回標準瀏覽器的json響應。

更新:
使用瀏覽器時,您首先提到需要登錄,返回的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"); 
+0

不,不工作。我試了兩個陳述:( – noob 2012-03-22 11:14:29

+0

@Creator,看到我的更新。 – yorkw 2012-03-22 20:26:16

+0

我試過但不工作 – 2015-08-13 12:10:39