Using Vert.x Web Client to send GET requests properly with headers - java

I have an internal endpoint that I am trying to send GET requests to with Vert.x Web Client with Java. So far, I am unable to successfully get any data back.
If I cURL the endpoint, it works just fine (these are internal endpoints). The service I am trying to send GET requests to requires a few headers , and data as well:
curl -H "Accept:application/json" -H "Content-Type:application/json" -H "alpha:192.168.10.20" -d '{"mutate":"*"}' http://my-endpoint.com/api/get-items
But if I try to use this in one of my router endpoints in Vert.x, I get an error:
WebClient webClient = WebClient.create(vertx);
webClient.get("http://my-endpoint.com/api/get-items")
.putHeader("Accept", "application/json")
.putHeader("Content-Type", "application/json")
.putHeader("alpha", "192.168.10.20")
.sendJsonObject(new JsonObject().put("mutate", "*"), ar -> {
if (ar.succeeded()) {
System.out.println("##### WEBCLIENT #####");
System.out.println(ar);
} else {
System.out.println("CAUSE: " + ar.cause().getMessage());
}
});
The error message I get from the else statement is:
CAUSE: Connection refused: localhost/127.0.0.1:80
What am I doing wrong? I've been using this for reference: Vert.x Web Client
===========================================
SOLUTION
===========================================
I had to change
webClient.get("http://my-endpoint.com/api/get-items")
to
webClient.post(80, "my-endpoint.com", "/api/get-items")
Also had to add .as(BodyCodec.jsonArray()) underneath the above line because the result I was getting was a Json Array.

You need to change
webClient.get("http://my-endpoint.com/api/get-items")
to
webClient.get(80, "my-endpoint.com", "/api/get-items")

Related

Java Akka actor's HTTP POST request not hitting the post path

I am creating a post request using akka version 2.6.17 and akka http 10.2.7. My system is bound to port 8080 and can receive post requests from Postman just fine. However, when sending a post request from within akka itself (an actor sending a post request), the POST path is never hit.
Here is the post request
public void postStockCheck(){
String data = "{\"id\": \"yes\"}";
HttpRequest.POST("http://localhost:8080/hello")
.withEntity(HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8, data));
}
Here is the path:
return route(
path("hello", () ->
post(() ->
entity(Unmarshaller.entityToString(), (string) -> {
System.out.println("request body: " + string);
return complete("Success");
})
)));
}
As mentioned, the path will work from postman. If I'm missing something, any help is appreciated!
In postStockCheck you have created a HttpRequest, but haven't fired it. To fire the request you could use singleRequest method from Http.
public void postStockCheck(ActorSystem system) {
String data = "{\"id\": \"yes\"}";
Http.get(system)
.singleRequest(HttpRequest.POST("http://localhost:8080/hello")
.withEntity(HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8, data)));
}
To get a better picture of firing the request and collecting responses, go through the docs.

Spring Boot REST API unrecognized token

I have a REST API and a WEB-app that makes request for that API. Both in Spring Boot.
I followed one of the many guides on this and testing the API in postman worked fine.
I also tested the API from my webapp and it also worked.
But when i run my API in docker with Traefik i get an error, but only from the webapp. Postman still works fine.
2020-10-27T13:31:10.334026053Z at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[na:na],
2020-10-27T13:32:34.827929610Z java.lang.RuntimeException: Could not read
requestcom.fasterxml.jackson.core.JsonParseException: Unrecognized token 'ssword': was expecting
(JSON String, Number, Array, Object or token 'null', 'true' or 'false')
In the request i post username and password as json in the body like this:
{
"username" : "user",
"password" : "dfgdhghdhdhfd"
}
This is the code that generates the request from the webapp:
JsonObject j = new JsonObject();
j.addProperty("username", API_USER);
j.addProperty("password", API_PASSWORD);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://myapi.local/login"))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(j.toString()))
.timeout(Duration.ofSeconds(2L))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
return response.headers().firstValue("Authorization").get();
Is there any chance it gets truncated somehow as it refers to the latter half of the 'password' key? I'm unsure of even where to begin getting information to assist you in helping me.
To summarize:
Localhost webapp and postman to localhost API: Works
Localhost postman to Docker API: Works
Localhost webapp to Docker API: Does not work

Watson Natural Language Understanding Java 401-not authorized

I'm trying to connect my Java application to the Watson NLU service. For a start, I tried to follow the tutorial from Bluemix. I created a service on Bluemix and imported the watson Java SDK. Using this tutorial code, I keep receiving 401 - not authorized responses. (Of course i changed username and password for the service).
I guess there's something missing, but i can't figure out what.
NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding(
NaturalLanguageUnderstanding.VERSION_DATE_2017_02_27,
"{username}",
"{password}"
);
String text = "IBM is an American multinational technology " +
"company headquartered in Armonk, New York, " +
"United States, with operations in over 170 countries.";
EntitiesOptions entitiesOptions = new EntitiesOptions.Builder()
.emotion(true)
.sentiment(true)
.limit(2)
.build();
KeywordsOptions keywordsOptions = new KeywordsOptions.Builder()
.emotion(true)
.sentiment(true)
.limit(2)
.build();
Features features = new Features.Builder()
.entities(entitiesOptions)
.keywords(keywordsOptions)
.build();
AnalyzeOptions parameters = new AnalyzeOptions.Builder()
.text(text)
.features(features)
.build();
AnalysisResults response = service
.analyze(parameters)
.execute();
System.out.println(response);
i had the same problems in node.js and solved it by adding the correct url of the api gateway to the NaturalLanguageUnderstanding service = new NaturalLanguageUnderstanding() object.
please keep in mind, that this depends on your region ..
regards
Leo
A 401 Unauthorized would suggest that there's an issue with the credentials that you're using to access the service. To rule this out, take a start by using the cURL tutorial from that same page:
curl -X POST \
-H "Content-Type: application/json" \
-u "{username}":"{password}" \
-d #parameters.json "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2017-02-27"
If, with that same username and password, you still receive a 401 Unauthorized error, then there's likely an issue with that username/password combination. Delete the tile in Bluemix and create a new one to get a new username/password, and give that a try.
If that does work fine, then there's an issue with how the username/password is being inserted into the code. Verify that you've replaced {username} and {password}, the final version should not have any curly brackets in it.

Cannot call Bitcoin RPC from Jersey HttpClient

im using dropwizard. From a resource i try to use bitcoin rpc via Jersey HttpClient.
using curl works like a charm:
$ curl --user user:password -X POST -d '{"jsonrpc": "1.0", "id":"curltest", "method": "getinfo", "params":
[] }' -H 'content-type: text/plain;' http://domain.name:18332/
But somehow using Jersey HTTP client from a resource doesnt work:
//init in run methode
final Client client = new JerseyClientBuilder(e).using(c.getJerseyClientConfiguration()).build(getName());
HTTPBasicAuthFilter httpBasicAuth = new HTTPBasicAuthFilter("user", "password");
client.addFilter(httpBasicAuth);
//From the resource
WebResource webRes = client.resource("http://domain.name:18332/");
webRes.header("content-type", "text/plain");
RPC_REQUEST rpc = new RPC_REQUEST("1.0", "curltest", "getinfo", new ArrayList<String>());
String response = webRes.post(String.class, JSONParserHelper.parseJSONToString(rpc));
JSONParserHelper.parseJSONToString(rpc) returns following string:
{"jsonrpc":"1.0","id":"curltest","method":"getinfo","params":[]}
Following error is caused in row "webRes.post":
! com.sun.jersey.api.client.UniformInterfaceException: Client response status: 500
EDIT: Using a wrong pw causes a 401. I guess the connection should be correct and the issue is somewhere else.
EDIT: Used -d instead of --data-binary
EDIT: As soon as Im home Ill dump the whole request from jersey http client.
Thank you
Bitcoin RPC does not support chunked encoding requests.
Since there was a bug in dropbox jersey libs till 0.8 you cannot disable it.
Since 0.8 you can disable it in the configuration file.
I had to migrate from 0.7 to 0.8 and add this in my configuration file.
httpClient:
...
chunkedEncodingEnabled: false
By the way a good migration overview: https://groups.google.com/forum/#!topic/dropwizard-dev/VInOW_ebiAc

500 server error?

I got quercus up and running on GAE and when I process this code I get Error: Server Error
<?php
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
$user="user";
$pass="pass";
try {
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass,
Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME);
} catch (Zend_Gdata_App_AuthException $ae) {
exit("Error: ". $ae->getMessage() ."\nCredentials provided were email: [$user] and password [$pass].\n");
}
?>
The thing is GAE is blocking every curl request and I can't make the request to the Spreadsheets
You cannot use curl on App Engine. You need to use URLFetch.

Categories

Resources