I'm getting error while posting JSON data in java, error states that, unable to find valid certification path to requested target.
I feel it's because of Authorization.
Can anyone please guide me how to write Authorization header in JSON for JAVA..
Share your code and detail explanation.
Below is the code to add header in request using okhttp.
private final OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("add api url")
.addHeader("Accept", "application/json")
.addHeader("Authorization", "add auth header here")
.build();
For reference here
Related
Im having problems on posting a multipart/formdata request to a REST api. The request returns an 400 Bad Request response.
This is how the request should look like. The link shows you a screenshot captured on a successful request by the web interface.
Successful request
This is the Java code I created.
public void importModel(String projectId, String modelId, MultipartFile file, String fileName) throws IOException {
MultipartBodyBuilder builder = new MultipartBodyBuilder();
builder.part("data", file.getBytes(), MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "form-data; name=data; filename=" + fileName);
MultiValueMap<String, HttpEntity<?>> parts = builder.build();
WebClient webClient = WebClient.builder()
.filters(exchangeFilterFunctions -> {
exchangeFilterFunctions.add(logRequest());
exchangeFilterFunctions.add(logResponse());
})
.build();
String request = webClient.post()
.uri(getBaseUriBuilder()
.pathSegment(getTeamSlug())
.path(API_PATH_PROJECTS)
.pathSegment(projectId)
.path(API_PATH_MODEL)
.pathSegment(modelId)
.path("/importasync")
.build())
.contentType(MediaType.MULTIPART_FORM_DATA)
.contentLength(file.getSize())
.header(HttpHeaders.AUTHORIZATION, getPrefixedAuthToken())
.body(BodyInserters.fromMultipartData(parts))
.exchange()
.flatMap(FlatService::apply)
.block();
return;
}
Any help is much appreciated. Thank in advance!
Have you tried to send the request with alternative Software like POSTMAN.
There you can check for the request properties that are being sent with the request
a 400 error can occur due to the following issues with your request
Wrong URL: Same as 404-Error a Bad Request is generated, when the user types in a wrong internet address or he adds special chars to the address.
Error full Cookies: If the Cookie inside your browser is to old or broken it can also be a 400.
Old outdated DNS-Entries: In your DNS-Cache could lie files that point to wrong or outdated IP- addresses
Too big files: when you try to upload very large files, the server can deny the request.
Too long header lines: the communication between the client and server is done with header information about the request. some servers set a limit to the header length.
Also if you can find out the more specific 400 error like this:
400.1: Invalid Destination Header
400.2: Invalid Depth Header
400.3: Invalid If Header
400.4: Invalid Overwrite Header
400.5: Invalid Translate Header
400.6: Invalid Request Body
400.7: Invalid Content
400.8: Invalid Timeout
400.9: Invalid Lock Token
If you are not the server admin you could ask him about specifications of the server. or use tools like postman where you can try to send requests to the server and find out more specific error codes.
I'm new to the java rest CXF client. I will make various requests to a remote server, but first I need to create a Ticket Granting Ticket (TGT). I looked through various sources but I could not find a solution. The server requests that I will create a TGT are as follows:
Content-Type: text as parameter, application / x-www-form-urlencoded as value
username
password
I create TGT when I make this request with the example URL like below using Postman. (URL is example). But in the code below, I'm sending the request, but the response is null. Could you help me with the solution?
The example URL that I make a request with POST method using Postman: https://test.service.com/v1/tickets?format=text&username=user&password=pass
List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJsonProvider());
WebClient client = WebClient.create("https://test.service.com/v1/tickets?format=text&username=user&password=pass", providers);
Response response = client.getResponse();
You need to do a POST, yet you did not specify what your payload looks like?
Your RequestDTO and ResponseDTO have to have getters/setters.
An example of using JAX-RS 2.0 Client.
Client client = ClientBuilder.newBuilder().register(new JacksonJsonProvider()).build();
WebTarget target = client.target("https://test.service.com/v1/tickets");
target.queryParam("format", "text");
target.queryParam("username", "username");
target.queryParam("password", "password");
Response response = target.request().accept(MediaType.APPLICATION_FORM_URLENCODED).post(Entity.entity(yourPostDTO,
MediaType.APPLICATION_JSON));
YourResponseDTO responseDTO = response.readEntity(YourResponseDTO.class);
int status = response.getStatus();
Also something else that can help is if you copy the POST request from POSTMAN as cURL request. It might help to see the differences between your request and POSTMAN. Perhaps extra/different headers are added by postman?
Documentation: https://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-JAX-RS2.0andCXFspecificAPI
Similar Stackoverflow: Is there a way to configure the ClientBuilder POST request that would enable it to receive both a return code AND a JSON object?
Above is what im trying to send
In java this is what I have
RequestBody formBody = new FormBody.Builder()
.add("param1", "abc")
.add("param2", "abc")
.add("param3", "abc")
.build();
Request request = new Request.Builder()
.url("http://localhost:3001/addsomething")
.post(formBody)
.build();
doesn't seem to work. I have OkHttpClient but I'm not sure how to use it to send the above result
What are you confused about? I'm a little unsure. I did a little research but it seems the only thing you're missing is a client, and then sending the request you've created and receive a response back.
To create a client, look at the most updated documentation on OkHttpClient, but this is what I found:
OkHttpClient client = new OkHttpClient();
And then send your request using that client using:
Response response = client.newCall(request).execute();
Then you can proceed to do something with that response.
All you have to understand is that you're creating a request (essentially asking the server for some information). Depending on your request, you'll get a response back (as in above), which you can then use to get whatever you're looking for.
I've created an account on OKTA environment here.
I searched on the net, but I couldn't find any examples on how to get access token from OKTA API. I'm looking for some example in "plain" Java code. But if there is something in any SDK, I'll be happy.
I tried to create an HTTP request (POST), to /token endpoint. I've used cliend_id and client_secret - in body. I've also tried to put in into header as basic authentication (before that, I encoded client_id:client_secret with Base64), but I still getting unauthorized (401).
OK I have a solution. The problem was wrong configuration on OKTA.
For those who needs working example, I'll share my tested code (believe me, it works)
public String GetToken() throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.build();
HttpRequest httpRequest = HttpRequest.newBuilder()
.uri(URI.create("https://YOUR_OKTA_DOMAIN/oauth2/default/v1/token"))
.headers("Content-type", "application/x-www-form-urlencoded",
"Authorization", "Basic " + Base64.getEncoder().encodeToString("CLIENT_ID:CLIENT_SECRET".getBytes()),
"Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(
"&grant_type=client_credentials" ))
.build();
HttpResponse<?> response = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
return response.body().toString();
}
On Okta you need to have created additional scope for Authorization Server. This scope should be default, or if you don't want to set default scope, you have to add it in body as
.POST(HttpRequest.BodyPublishers.ofString(
"&grant_type=client_credentials" +
"scope=SCOPE_NAME"))
I am using Simple_JWT for authentication in Djangorestframework back-end. when a user is logged in the following url will log them out:
http://130.50.85.130/rest-auth/logout/
it requires no data.
now I am trying to post similar request using Okhttp.
When I am trying the following, it breaks:
Request post_request = new Request.Builder()
.url(url_str)
.addHeader("Authorization", "JWT "+token)
.build();
Note that it doesn't have a body and it has token in the header. I am not sure if this post request needs any body or needs header containing token.
I guess the bottom line of my question is how to send a request for log out using okhttp from a user that is already signed in,
Please advise,
Thanks,