输入凭据然后 post JSON 到 api java

Enter credentials then post JSON to api java

我一直在想办法 post 一个 JSON 到外部 api。问题是不想对用户名和密码进行硬编码,而是让拥有 API.I 有效凭据的任何人都可以使用它具有适用于硬编码凭据的代码,但我希望用户输入用户名和每个请求的密码。我想使用基本的身份验证浏览器对话框来捕获凭据,然后 post JSON 但我无法弄清楚。

这是我当前的代码

public class RestService {
    String Username="admin";
    String Password="pass";

  public String createPost() throws AuthenticateException,ClientHandlerException {

String url = "https://someapi.net/rest/api/2/issue/";

Client client = Client.create ();

client.addFilter (new HTTPBasicAuthFilter(Username, Password));
WebResource webResource= client.resource(url);
//--INPUT is formatted a bit different In my app but I just can't show it
String input = "{
    "fields": {
       "project":
       {
          "key": "TEST"
       },
       "summary": "REST ye merry gentlemen.",
       "description": "Creating of an issue using project keys and issue type names using the REST API",
       "issuetype": {
          "name": "Bug"
       }
   }
}"

ClientResponse response = webResource.type("application/json").post(ClientResponse.class,input);
string output = response.getEntity(String.Class)

我找到了这个,并被告知它可能有用,但我不确定我在代码中输入它的位置。

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));  //Java 8
connection.setRequestProperty("Authorization", "Basic "+encoded);

您似乎想使用 Jersey Client API 创建一个具有基本身份验证的 Jira 问题,那么您可以在 header 中传递凭证,如下所示:

String encoded = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));

ClientResponse response = webResource.type("application/json")
        .header("Authorization", "Basic " + encoded) // put the credential in header
        .post(ClientResponse.class,input);