简体   繁体   中英

JAVA - POST API CALL

I'm trying to call an API with basic authorization but without success.

ClientConfig clientConfig = new ClientConfig();

HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("username", "password");
clientConfig.register( feature) ;

clientConfig.register(JacksonFeature.class);

Client client = ClientBuilder.newClient( clientConfig );
String URL = "http://localhost:8080/teste/" + taskId + "/start";
WebTarget webTarget = client.target(URL);

Invocation.Builder invocationBuilder =  webTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();

System.out.println(response.getStatus());
System.out.println(response.getStatusInfo());

if(response.getStatus() == 200)
{
    System.out.println(response.getStatus());
}

I'm getting many errors like:

Could not find a suitable constructor in org.glassfish.jersey.message.internal.SourceProvider$SaxSourceReader class. java.lang.IllegalArgumentException: Errors were discovered while reifying SystemDescriptor(

Can you help me please? Some tips?

Greetings

String URL = "http://localhost:8080/teste/" + taskId + "/enable"; HttpPut request = new HttpPut(URL);

    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(
            AuthScope.ANY,
            new UsernamePasswordCredentials("user", "password")
    );

    try (CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(provider)
            .build()) {
        try (CloseableHttpResponse response = httpClient.execute(request)) {

            // 401 if wrong user/password
            System.out.println(response.getStatusLine().getStatusCode());

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // return it as a String
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            }

        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

I'm using this solution now and its work, but i need to send a raw body in this request, how i can do that?

Any tip?

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM