java - 输入凭据,然后将 JSON 发布到 api java

标签 java json spring post basic-authentication

我一直在尝试找出一种将 JSON 发布到外部 api 的方法。问题是不想对用户名和密码进行硬编码,而是让任何拥有 API 有效凭据的人使用它。我有适用于硬编码凭据的代码,但我希望用户输入用户名和密码根据要求。我想使用基本的身份验证浏览器对话来捕获凭据,然后发布 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);

关于java - 输入凭据,然后将 JSON 发布到 api java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58907090/

相关文章:

java - 自动滚动代码不起作用 : cannot find symbol

java - Android ThreadPoolExecutor 和 join()

Java流的迭代器强制flatmap在获取第一项之前遍历子流

javascript - 协作式 JSON 查看器/解析器

java - spring-social-twitter,@Value 不连接属性

java - Spring 中读取属性文件的不同行为

java - 选中 RecyclerView ListView 中的多个复选框,但使用无法正常工作的 notifyDataSetChanged 刷新列表

java - 如何从 JSON 数组中获取随机对象

ios - 如何在 iOS Swift 中使用 JSON 数据在表格 View 中显示标题(类型)?

Spring 3.0 错误 : java. lang.NoClassDefFoundError: org/aspectj/lang/NoAspectBoundException