How to send x-www-form request on java? - java

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.

Related

Program stuck in socketRead0 method when requesting with OkHttp

I developed a Java library for Twitter API here using OkHttp3 4.8.1.
Unfortunately, it looks like after having sent a request, once everything is finished, the program never stops and is stuck in SocketInputStream.
When not using cache, it is stuck in waitForReferencePendingList method of Reference class instead :
I tried everything, closing connection explicitly in my code like this, updating the version of OkHttp, but still the same. Any idea ?
If needed, here is the full code where the request is done, in summary :
Request request = new Request.Builder()
.url(url)
.get()
.headers(Headers.of("Authorization", "Bearer " + bearerToken))
.build();
OkHttpClient client = new OkHttpClient.Builder().build()
Response response = client.newCall(request).execute();
String stringResponse = response.body().string();
return Optional.ofNullable(TwitterClient.OBJECT_MAPPER.readValue(stringResponse, classType));
Finally adding client.connectionPool().evictAll(); elsewhere (in my post request to get a bearer token) solved the problem !

SparkJava GET Handler Returning NULL After Serialization of Long

I'm trying to write a simple server with SparkJava but I am having considerable difficulty serialize a long using Gson and transmitting the JSON to an OkHttp client program inside a GET handler. The server returns NULL, more specifically response.body.string() is
<html><body><h2>404 Not found</h2></body></html>
Any ideas on what the issue could be? thanks.
Here is the GET handler:
get("routingEngine/getDefaultRoute/distance", (request,response) ->{
response.type("application/json");
long distance = 100;
return gson.toJson(distance);
});
Here is the client code making the simple request (please disregard the parameters (requestParameters) being passed in along with the request, they just provide information to an irrelevant before filter):
// build url
HttpUrl url = new HttpUrl.Builder()
.scheme("http")
.host("127.0.0.1")
.port(4567)
.addPathSegment("routingEngine")
.addPathSegment("getDefaultRoute")
.addPathSegment("distance")
.build();
// build request
Request getDefaultRouteDistanceRequest = new Request.Builder()
.url(url)
.post(RequestBody.create(JSON,gson.toJson(requestParameters)))
.build();
// send request
Call getDefaultRouteDistanceCall = httpClient.newCall(getDefaultRouteDistanceRequest);
Response getDefaultRouteDistanceResponse = getDefaultRouteDistanceCall.execute();
// parse response
// testing
System.out.println(getDefaultRouteDistanceResponse.body().string());
The last line leads to the following output
<html><body><h2>404 Not found</h2></body></html>
The endpoint you created was a GET endpoint and the call being made is for POST.

How to remove User-Agent String when I make a http post call?

I want to remove "User-Agent" property from my post httprequest.
I'm using okhttpclient.
Can anyone help me with snippet of code?
This will remove it for any request the client sends.
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(chain -> chain.proceed(chain.request().newBuilder()
.removeHeader("user-agent")
.build()))
.build();

Java Unirest sends POST request with empty JSON to server running on localhost but works fine when sending the same request to cloud server?

I am building an agent in Java which has to solve games using a planner. The planner that I am using runs as a service on the cloud, and thus anybody can send HTTP requests to it and get a response. I have to send to it a JSON with the following content: {"domain": "string containing the domain's description", "problem": "string containing the problem to be solved"}. As a response I get a JSON that contains the status and the result, which might be a plan or not, depending on whether there was some problem or not.
The following piece of code allows me to call the planner and receive its response, retrieving the JSON object from the body:
String domain = readFile(this.gameInformation.domainFile);
String problem = readFile("planning/problem.pddl");
// Call online planner and get its response
String url = "http://solver.planning.domains/solve";
HttpResponse<JsonNode> response = Unirest.post(url)
.header("accept", "application/json")
.field("domain", domain)
.field("problem", problem)
.asJson();
// Get the JSON from the body of the HTTP response
JSONObject responseBody = response.getBody().getObject();
This code works pefectly fine and I don't have any kind of problem with it. Since I have to do some heavy testing on the agent, I prefer to run the server on localhost, so that the service doesn't get saturated (it can only process one request at a time).
However, if I try to send a request to the server running on localhost, the body of the HTTP request that the server receives is empty. Somehow, the JSON is not sent and I am receiving a response that contains an error.
The following piece of code illustrates how I am trying to send a request to the server running on localhost:
// Call online planner and get its response
String url = "http://localhost:5000/solve";
HttpResponse<JsonNode> response = Unirest.post(url)
.header("accept", "application/json")
.field("domain", domain)
.field("problem", problem)
.asJson();
For the sake of testing, I had previously created a small Python script that sends the same request to the server running on localhost:
import requests
with open("domains/boulderdash-domain.pddl") as f:
domain = f.read()
with open("planning/problem.pddl") as f:
problem = f.read()
data = {"domain": domain, "problem": problem}
resp = requests.post("http://127.0.0.1:5000/solve", json=data)
print(resp)
print(resp.json())
When executing the script, I get a correct response, and it seems that the JSON is sent correctly to the server.
Does anyone know why this is happening?
Okay, fortunately I have found an answer for this issue (don't try to code/debug at 2-3AM folks, it's never going to turn out right). It seems that the problem was that I was specifying what kind of response I was expecting to get from the server instead of what I was trying to send to it in the request's body:
HttpResponse response = Unirest.post(url)
.header("accept", "application/json")...
I was able to solve my problem by doing the following:
// Create JSON object which will be sent in the request's body
JSONObject object = new JSONObject();
object.put("domain", domain);
object.put("problem", problem);
String url = "http://localhost:5000/solve";
<JsonNode> response = Unirest.post(url)
.header("Content-Type", "application/json")
.body(object)
.asJson();
Now I am specifying in the header what type of content I am sending. Also, I have create a JSONObject instance that contains the information that will be added to the request's body. By doing this, it works on both the local and cloud servers.
Despite of this, I still don't really get why when I was calling the cloud server I was able to get a correct response, but it doesn't really matter now. I hope that this answer is helpful for someone who is facing a similar issue!

How to get response from GET-request to API in okhttp?

How can i get some response from API through GET-request?
The way i'm sending GET:
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(5, TimeUnit.SECONDS);//Connect timeout
client.setReadTimeout(5, TimeUnit.SECONDS);//Socket timeout
Request request = new Request.Builder().url(String.valueOf(message)).build();
Response response = client.newCall(request).execute();
The way i'm trying to get response:
response.message();
What i get:
OK
What i need to get from API:
OK|ID (Example: OK|2122988149)
You should try:
response.body().string()

Categories