有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是如何使用Web API登录的

我正在编写一个web应用程序,它可以显示Sonarqube的代码气味结果,但我也希望它有时可以创建自定义规则。目前,我能够使用Java中的HTTPClient或Js中的XMLHttpRequest从服务器获取数据。然而,我真的被贴到服务器上的消息卡住了

在Js中,我尝试了以下代码登录:(我的chrome中已禁用CORS)

request.open("POST", "http://localhost:9000/api/authentication/login?login=admin&password=admin", true);
request.send();

响应状态代码为200,这是成功的。但是,当我尝试执行某些需要许可的操作时

request.open("POST", "http://localhost:9000/api/qualityprofiles/copy?fromKey=" + fromKey + "&toName=" + name, true);
request.send();

结果是401,未经授权

经过一些研究,我把代码改为

var base64encodedData = ("admin:admin").toString('base64');
request.open("POST", "http://localhost:9000/api/qualityprofiles/copy?fromKey=" + fromKey + "&toName=" + name, true);
request.setRequestHeader("Authorization", "Basic " + base64encodedData);
request.send();

响应为405,未找到任何方法

经过进一步研究,有人提到request.withCredentials应该设置为true。我加入了,然后我又遇到了CORS问题。(禁用CORS时)

(我对Sonarqube API有点困惑。我之所以这么说,是因为在我看来,该API的目的是简化在外部使用Sonarqube服务器的方法。但是,由于它不允许CORS,这是否意味着我不能在自己的网页上使用该API?)

由于Js中没有运气,我转而使用Java

在Java中,我运行了以下命令:(我也完成了登录)

HttpPost post = new HttpPost("http://localhost:9000/api/qualityprofiles/copy?fromKey=AV7dToVK_BWPTtE1c9vU&toName=testtt");
try(CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(post);) {

        System.out.println(response.getStatusLine());
}

我得到:

HTTP/1.1 401 

然后我改变我的代码跟随这个关于Basic Authentication with the API的链接

CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials
     = new UsernamePasswordCredentials("admin", "admin");
provider.setCredentials(AuthScope.ANY, credentials);

HttpClient client = HttpClientBuilder.create()
      .setDefaultCredentialsProvider(provider)
      .build();

HttpResponse response = client.execute(
      new HttpPost("http://localhost:9000/api/qualityprofiles/copy?fromKey=AV7dToVK_BWPTtE1c9vU&toName=testtt"));
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);

再一次,401

总之,我的问题是:如何使用Java代码或Js代码(首选)将消息发布到具有授权的SonarQube服务器

感谢您的帮助

更新

我现在尝试使用curl,这是我在终端中运行的

curl -X POST -u deb3dd4152c571bcdb7b965e1d99b23a4e5c9505: http://localhost:9000/api/qualityprofiles/copy?fromKey=AV7dToVK_BWPTtE1c9vU&toName=test_file

我得到了这个回答,我不知道是怎么得到的

{"errors":[{"msg":"The 'toName' parameter is missing"}]}

第二次更新CURL

我跑:

curl -X POST -F "fromKey=AV7dToVK_BWPTtE1c9vU;toName=test_file" -v -u deb3dd4152c571bcdb7b965e1d99b23a4e5c9505: http://localhost:9000/api/qualityprofiles/copy

结果:

*   Trying ::1...
* Connected to localhost (::1) port 9000 (#0)
* Server auth using Basic with user 'deb3dd4152c571bcdb7b965e1d99b23a4e5c9505'
> POST /api/qualityprofiles/copy HTTP/1.1
> Host: localhost:9000
> Authorization: Basic ZGViM2RkNDE1MmM1NzFiY2RiN2I5NjVlMWQ5OWIyM2E0ZTVjOTUwNTo=
> User-Agent: curl/7.49.1
> Accept: */*
> Content-Length: 179
> Expect: 100-continue
> Content-Type: multipart/form-data; boundary=------------------------c22bb5dd76f44ac4
> 
< HTTP/1.1 100 
< HTTP/1.1 400 
< Content-Type: application/json
< Content-Length: 56
< Date: Wed, 04 Oct 2017 00:43:47 GMT
< Connection: close
< 
* Closing connection 0
{"errors":[{"msg":"The 'toName' parameter is missing"}]}

共 (2) 个答案

  1. # 1 楼答案

    这段代码来自C# 字符串url=”http://localhost:9000/api/project_badges/quality_gate?project=projectName“

            HttpClient client = new HttpClient();
    
            var byteArray = Encoding.ASCII.GetBytes("username:password");
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
            string responseString = string.Empty;
            var response = client.PostAsync(url, null).Result;
            if (response.IsSuccessStatusCode)
            {
                var responseContent = response.Content;
                responseString = responseContent.ReadAsStringAsync().Result;
            }
    
  2. # 2 楼答案

    对于任何有同样问题的人。我已经让它在Java代码上工作,这是我的代码

    HttpPost post = new HttpPost("http://localhost:9000/api/qualityprofiles/copy?fromKey=AV7dToVK_BWPTtE1c9vU&toName=testtt");
    post.setHeader("Authorization", "Basic ZGViM2RkNDE1MmM1NzFiY2RiN2I5NjVlMWQ5OWIyM2E0ZTVjOTUwNTo="); 
    try(CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(post);) {
    
        System.out.println(response.getStatusLine());
    }
    

    你可能会注意到我添加了一行设置标题。我以前也做过类似的事情,将我的登录名和密码编码为base64格式,但它们都无法正常工作。这个工作编码字符串取自CURL方法。(来自我的第二次更新)

    我尝试了一些在线base64编码和解码工具,但结果与我从CURL方法得到的结果不匹配,所以如果您在这方面遇到困难,请运行CURL以获取编码的头并将其传递进来!如果有人能解释一个更好的版本,那就太好了

    此外,我仍然对Js版本的运行感兴趣。如果你知道答案,请分享