如何在Java中使用身份验证进行有效的rest调用

如何在Java中使用身份验证进行有效的rest调用,java,rest,authentication,https,Java,Rest,Authentication,Https,我试图编写一个java类文件,该文件使用HTTP Rest调用(本例中为post)对系统进行身份验证 我尝试了以下代码,但出现了一个错误: {"errors":[{"message":"The request could not be understood","developerMessage":"The request body did not contain valid JSON"}]} 这是我的密码: public class simplePost { private fina

我试图编写一个java类文件,该文件使用HTTP Rest调用(本例中为post)对系统进行身份验证

我尝试了以下代码,但出现了一个错误:

{"errors":[{"message":"The request could not be understood","developerMessage":"The request body did not contain valid JSON"}]}
这是我的密码:

public class simplePost {

    private final String USER_AGENT = "Mozilla/5.0";

    public static void main(String[] args) throws IOException {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("https://xxxxxx/xxxxx/token");

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("username", "password"));

        List nameValuePairs = new ArrayList(1);
        nameValuePairs.add(new BasicNameValuePair("username", "xxxxxxxxxx")); 
        nameValuePairs.add(new BasicNameValuePair("password", "xxxxxx"));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
    }
}
我不知道为什么会出现这个错误。 当我在Postman或AdvanceRestClient中输入URI和登录信息时,我得到了正确的响应

我能得到一些帮助吗

谢谢


ironmantis7x

错误消息显示“请求正文未包含有效的JSON”。检查post正文(json)-特别是-post.setEntity(新的UrlEncodedFormEntity(nameValuePairs));UrlEncodedForm不是JSON。为什么凭证会同时进入POST正文和Auth标头?我如何使UrlEncodedForm json?错误消息说“请求正文不包含有效的json”。检查post正文(json)-特别是-post.setEntity(新的UrlEncodedFormEntity(nameValuePairs));UrlEncodedForm不是JSON。为什么凭证会同时进入POST正文和Auth头?我如何制作URLEncodedFormJSON??