Http Get请求无效

时间:2015-08-08 16:32:51

标签: scala httpclient

我正在尝试使用它的rest api从apache ranger获取xml数据。这是我的代码

    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 个答案:

答案 0 :(得分: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())

在请求中设置身份验证。

由于