Use resteasy with user and password - java

I am trying to convert this line to resteasy stuff.
curl -X GET --digest -u myuser:mypassword --header 'Accept:application/json; charset=utf-8' http://localhost:8087/v2/servers/_defaultServer_/vhosts/_defaultVHost_/applications/live/instances
this is how I am trying to connect to that endpoint
clientREST = new ResteasyClientBuilder().build();
clientREST.register(new BasicAuthentication(userWowza, passWowza));
String targetStr = "http://" + host + ":" + portEndpoint + endPoint + red5App + "/instances";
System.out.println(targetStr);
ResteasyWebTarget target = clientREST
.target(targetStr);
Response response = target.request().post(Entity.entity("", "application/json"));
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
But I get HTTP error code : 401. So it is like user and password is no working. Am I sending the headers correctly?
Update
So I couldnt find any example of resteasy with digest auth, so I found that wowza seems to suppport basic and digest at the same time

Actually your curl uses --digest not BASIC authentication. So it looks like Server does not accept BASIC Authorization schema.

Related

cURL + Java -- CPAS Request -- Suggestion Please

Explination
I am working on a Java App that sends a text message via a CPAS API (Similar to Tweepy). I am using CURL to request the message send. The request from Java seems to be sent but I am getting a 401 code. I'm assuming there is an issue with the encoding of my Authentication for the request. The code is as follows:
URL url = new URL("https://api.zang.io/v2/Accounts/ACe1889084d37de951ef064200aecbe4b2/SMS/Messages");
String auth = AUTH + ":" + TOKEN;
String encodeedAuth = Base64.getEncoder().withoutPadding().encodeToString(auth.getBytes());
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setRequestMethod("POST");
http.setDoOutput(true);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("Authorization", "Basic " + encodeedAuth);
String data = "From=+14132698029&To=17817381451&Body=New Test";
byte[] out = data.getBytes(StandardCharsets.UTF_8);
OutputStream stream = http.getOutputStream();
stream.write(out);
System.out.println(http.getResponseCode() + " " + http.getResponseMessage());
http.disconnect();
"""
An HTTP 401 response is commonly an HTTP endpoint authorization failure. The best way to see why your auth credentials are failing is to capture the request/response pair in transit (at the receiving end would be optimal) and then compare that request/response pair to one that works.

How do we consume rest api with Http basic authentication in spring?

I want to consume rest api from url with http basic authentication that returns a big json & then i want to parse that json without POJO to get some values out of it. How can i achieve that in java spring?
I know this is common question but i could not get proper solution that worked for me.
Please help me someone.
Using the Apache HttpClient, the following Client Code snipped has been copied from the following URL. The comments have been added by myself.
https://www.baeldung.com/httpclient-4-basic-authentication
HttpGet request = new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION);
// Combine the user and password pair into the right format
String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
// Encode the user-password pair string in Base64
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(StandardCharsets.ISO_8859_1));
// Build the header String "Basic [Base64 encoded String]"
String authHeader = "Basic " + new String(encodedAuth);
// Set the created header string as actual header in your request
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
assertThat(statusCode, equalTo(HttpStatus.SC_OK));

Calling a WS with Postman is done, but not from Java code

I did a Post request by using Postman and I got a response, but when did the same resquest using OkHttpClient (same problem with HttpsURLConnection) in java I got a connection refused exception.
Below is my code (with fake data) :
OkHttpClient client = new OkHttpClient();
String req = "<?xml version=\"1.0\"?>\r\n" +
"<ApplicantTestRequest\r\n" +
"PositionID=\"48939014-b24f-4d74-8a44-9913cd9f8936\"\r\n" +
"ThirdPartyCandidateID=\"4152ab4r\"\r\n" +
"FirstName=\"Danny\"\r\n" +
"LastName=\"Givaty\"\r\n" +
"UserName=\"dannyg\"\r\n" +
"Password=\"2sEr#d!w#\"\r\n" +
"email=\"dannyg#careerharmony.com\"\r\n" +
"Telephone=\"5558586858\"\r\n" +
"Source=\"LinkeIn\"\r\n" +
"SkipToFirstRecruiterComponent = \"1\"\r\n" +
"Gender = \"1\"\r\n" +
"/>";
RequestBody reqbody = RequestBody.create(null, req);
Request request = new Request.Builder()
.url("https://staging.direct-assessment.net/RomaTestUI/forms/xmlregistrationandtestentry.aspx?XMLReadType=1")
.method("POST",reqbody)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
int responseCode = response.code();
System.out.println("Response Code : " + responseCode);
The result I got is :
Exception in thread "main" java.net.ConnectException: Failed to connect to staging.direct-assessment.net/185.52.110.193:443
...........
Caused by: java.net.ConnectException: Connection refused: connect
Any suggestion ?
I can see below reason for this, I am also including a possible solution -
The issue could be related to HTTP_TRANSPORT_VERSION, can you check what version is sent via Postman and what is sent from the Java program. If the versions are different then set the HTTP_TRANSPORT_VERSION (similar to that of Postman request) in your java call.

Authentication Details Not Provided REST API POST Request

I'm posting to an API server and I'm getting the following reply:
Server Response: {"detail":"Authentication credentials were not provided."}
I'm writing the requests in Java and I'm not sure exactly why it's saying credentials were not provided.
Here is a snippet of my code:
hconn.setRequestProperty("Content-Type", "application/json");
hconn.setRequestProperty( "Accept", "application/json" );
if( urlconn instanceof HttpsURLConnection )
{
String encoded = new String(Base64.getEncoder().encode( ( username + ":" + password).getBytes()));
String auth = "Basic " + encoded;
urlconn.setRequestProperty("Encoded Authorization", auth );
}
Where hconn is of type HttpURLConnection
This is the only relvant snippet that you guys need. Are there properties i'm missing to set here?
I know the server response is from a Django framework but the documentation is not clear on spotting what IS required to prevent this.
Any help appreciated.
Authorization is the correct request header name and not 'Encoded Authorization'. So, you should set
urlConn.setRequestProperty("Authorization", auth);

can escaping ruin my http GET request?

I try to trigger an http GET request
It should be as follows:
https://www.my_service.com/myRequest?from=x%3A34.78104114532471+y%3A31.243920719573723&to=x%3A34.77901339530945+y%3A31.242416368424312&
I wrote this code
webResource.accept("application/json");
ClientResponse response = webResource.path("myRequest")
.queryParam("from", "x%3A34.78104114532471+y%3A31.243920719573723")
.queryParam("to", "x%3A34.77901339530945+y%3A31.242416368424312")
.accept(MediaType.APPLICATION_JSON_TYPE)
.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
which generates this url:
https://www.my_service.com/myRequest?from=x%3A34.78104114532471+y%3A31.243920719573723&to=x%3A34.77901339530945+y%3A31.242416368424312&
but this returns 404 error.
I have tried the two urls in the browser.
The only difference is + replaced by %2B
+ works for me but %2B doesn't.
how can i make the code not replace + with %2B?
Strangely I had to replace + with space:
.queryParam("from", "x%3A34.78104114532471 y%3A31.243920719573723")
.queryParam("to", "x%3A34.77901339530945 y%3A31.242416368424312")

Categories

Resources