2015-08-08 130 views
1

我想從apache ranger使用它的rest api獲取xml數據。這裏是我的代碼Http獲取請求不起作用

val httpclient = new DefaultHttpClient() 
    val auth=new AuthScope(host,AuthScope.ANY_PORT) 
    val credentials=new UsernamePasswordCredentials(username, password) 
    httpclient.getCredentialsProvider() 
      .setCredentials(auth, credentials) 
    val httpget = new HttpGet("http://localhost:6080/service/public/api/repository/1") 
    httpget.setHeader("Accept", "application/xml") 
    val response = httpclient.execute(httpget) 
    val entity = response.getEntity 
    if (entity != null) { 
     val in = new BufferedReader(new InputStreamReader(entity.getContent())) 
     var line = in.readLine() 
     var response = new StringBuffer() 
     while (line != null) { 
     response.append(line) 
     line = in.readLine() 
     } 
     in.close() 
     println(response.toString()) 
    } 

如果我從瀏覽器中打開此網址,它顯示結果很好。但在代碼的情況下,它會返回HTML。

任何幫助?

+1

這個html說什麼?什麼關於認證? – Ashalynd

+0

它說用戶不存在 – user3313379

+0

這個工作正常使用這種格式的curl命令 curl http://my_url.net?param1=12¶m2=777 - 首頁「授權:基本XXX」其中xxx是編碼用戶名:密碼 – user3313379

回答

1

嘗試此代碼

val httpclient = new DefaultHttpClient() 
    val httpget = new HttpGet("url") 
    httpget.addHeader(BasicScheme.authenticate(
     new UsernamePasswordCredentials("user", "pass"), 
     "UTF-8", false)) 
    httpget.setHeader("Accept", "application/json") 
    val response = httpclient.execute(httpget) 
    EntityUtils.toString(response.getEntity()) 

在請求設置認證。

謝謝