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()
Related
I'm using OkHttpClient in a Java service and I'm trying to send a get request with an Authorization header.
For some reason, the below fails with response code 401 as if the token isn't sent within the headers.
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder();
.url(url)
.header("Authorization", "Bearer " + token)
.build();
var response = client.newCall(request).execute()
I also tried out using the headers builder param and passing a Headers object containing Authorization Bearer some-token, and also tried with addHeader("Authorization", token) but same happens.
OkHttpClient version: 4.9.2
What's wrong with the above code? Is OkHttpClient stripping off the Authorization header for some reason?
I have to request data from an API but the API needs a JSON in the request body and it has to be sent using the GET method. My project uses the Java 11 HttpClient library so I want solutions that only include using this library. How do I send the body in GET method?
HttpRequest request = HttpRequest.newBuilder(uri)
.header("Content-Type", "application/json")
.GET(BodyPublishers.ofString(jsonObject.toString()))
.build();
HttpClient client = AppHttpClient.getInstance();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
Code issue
Builder class doesn't have a predefined GET method with the ability to pass request body. In this case just use more generic approach:
HttpRequest request = HttpRequest.newBuilder(uri)
.header("Content-Type", "application/json")
.method("GET", BodyPublishers.ofString(jsonObject.toString()))
.build();
HttpClient client = AppHttpClient.getInstance();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
General
Usually, passing body in the GET request is not recommended, so I would recommend reconsidering your API design. Instead of a body, you can use URL query parameters or think about using the POST method if the request body is quite big and can't be mapped to the query parameters.
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 am new to REST API and working with servers in general and I am trying to make a simple client-server application. I am using Jersey.
Client sends some data to server, server receives the data and shows it on the desired uri and vice versa.
The vice-versa part of receiving the data hosted on server is working fine, but I am not able to send data to server.
I have tried POST like this:
#POST
#Path("/something")
#Consumes("application/x-www-form-urlencoded")
public void getSomething(){
}
And my client side code looks something like this:
Client client = Client.create();
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
WebResource resource = client.resource("http://localhost:8080/artifact/rest/something");
ClientResponse response = resource.type("application/x-www-form-urlencoded").post(ClientResponse.class, formData);
System.out.println(response);
I am trying to send a string or json type object to server and it should show it on that url. But I am not able to do so.
I'd appreciate if someone could help me in this.
Edit
I would also appreciate if someone could tell me how to send data to server with code like this.
Try using this format for the jersey server side although whatever you are using is the same:
#POST
#Path("your path")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
For the client side, try using this.
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url + "/rest/something");
post.addHeader("Accept" , "application/json");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name1", "val1"));
params.add(new BasicNameValuePair("name2", "val2"));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpClient.execute(post);
String out = EntityUtils.toString(response.getEntity());
Your getSomething is not returning anything. This translates to a 204 No Content response: The operation was successful (the 2xx of the code indicates this) but there is nothing to return.
If you want to return something, change the return type from void to Response.
#POST
#Path("/something")
#Consumes("application/x-www-form-urlencoded")
#Produces("text/plain")
public Response getSomething() {
return Response.ok("Success!").build();
}
This will return the HTTP status code 200 OK with Success! as the content of the response body.
But you probably want to somehow use the content of the request. Take a look at jax-rs retrieve form parameters for how you can do this.
I'm trying to post to facebook via java, and it works, but only on the second POST request. The first always returns a HTTP 400, while the second works fine.
final URL url = new URL("https://graph.facebook.com/me/feed" + urlParameters);
String facebookPostUrl = url.toString();
Client client = Client.create();
WebResource facebookPost = client.resource(facebookPostUrl);
ClientResponse response = facebookPost.get(ClientResponse.class);
response.close();
The parameters I'm passing in are correct. If I copy the request into a browser it works just fine.
I should note that I'm performing a GET request with ClientResponse, and signalling to FB that it is a post by using the &method=POST in the URL.
The 400 response :
response-code GET https://graph.facebook.com/me/feed?access_token=TOKEN&link=http%3A%2F%2Fbit.ly%2F1dHkdAV&method=post&caption=gigj returned a response status of 400 Bad Request
I removed the access token for privacy.
Any help is appreciated!