I make a post request using okHttp with the next code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
The server response with:
response
{
message: {
user: {
id: 12,
name: 'myName'
},
message: 'Usuario creado con éxito.',
code: 200
}
}
But the response that okHttp gives me is:
Response{protocol=http/1.1, code=200, message=OK, url=http://localhost:2222/api/users}
There isn´t a way to get what the server sends me with okHttp?
If the response is sent in the body you can get it with:
response.body().string();
You just had to look on the documentation
¡Salud!
What you are getting is the header of response object. you can access the body of response by:
response.body().string();
full code:
final MediaType JSON = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = null;
response = client.newCall(request).execute();
String responseBody = response.body().string();
Related
Really strange as I copy paste the code sample from the sendinblue API doc:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/octet-stream");
RequestBody body = RequestBody.create(mediaType,"\"updateEnabled\":false,\"email\":\"example#email.com\"}");
Request request = new Request.Builder()
.url("https://api.sendinblue.com/v3/contacts")
.post(body)
.addHeader("accept", "application/json")
.addHeader("content-type", "application/json")
.addHeader("api-key", "xxxxxxxxxxxxxxxxxx")
.build();
Response response = client.newCall(request).execute();
The response is:
response code is: 406
response message is: Not Acceptable
response body is: {"code":"not_acceptable","message":"Unacceptable content-type"}
I use this Java client:
<dependency>
<groupId>com.sendinblue</groupId>
<artifactId>sib-api-v3-sdk</artifactId>
<version>3.0.1</version>
</dependency>
You need to set the content-type in as JSON (application/json).
I'm trying to parse a Json data with the following code:
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url("http://datamall2.mytransport.sg/ltaodataservice/BusServices")
.method("GET", null)
.addHeader("AccountKey", "XXXX==")
.addHeader("accept", "application/json")
.build();
Response response = client.newCall(request).execute();
The two errors that I'm facing are:
error: cannot find symbol method newBuilder()
and
unhandled exception error for .execute();.
According to https://square.github.io/okhttp/ you just need to do:
OkHttpClient client = new OkHttpClient();
I am unable to get MIME for a message using $value like specified in the documentation. How to get MIME?
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.header("Authorization", "Bearer " + accessToken)
.url("https://graph.microsoft.com/v1.0/me/messages/k4ZDQ5LTgzMTYtNGZhYS04ZTU3LWZhMjFmZmUzNmE1YwBGAAAAAABzUENX1K4kR6h6KAAA7ENoUb5BySZFX6KemUxNwAAAv_a5nAAA=/?value")
.build();
Response response = null;
String body;
try {
response = client.newCall(request).execute();
body = response.body().string();
Your URLs are incorrect, they're using /?value but should be using /$value ($ not ?). The $value is part of the path, not a query param:
https://graph.microsoft.com/v1.0/me/messages/4aade2547798441eab5188a7a2436bc1/$value
I'm making a request to a website. However, I keep getting a returned JSON of {"error":"invalid_client"}. Additionally, when I navigate to the URL I'm making the request to through a web browser it shows HTTP ERROR 405.
From what I read on those errors that might mean that my request isn't structured correctly.
According to the API's documentation, this is an example of the request type I'm trying to do:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "client_secret={your_client_secret}&client_id={your_client_id}&code={your_authorization_code}&grant_type=authorization_code&redirect_uri={your_redirect_uri}");
Request request = new Request.Builder()
.url("https://api.website.com/v2/oauth2/token")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("cache-control", "no-cache")
.build();
Response response = client.newCall(request).execute();
From what I can tell mine should be doing the same thing, just a little differently.
Here is a Pastebin of my doInBackground method (I'm using AsynchTask). Here is the more applicable part:
OkHttpClient client = new OkHttpClient();
// A section here gets strings from a JSON file storing values such as client_id
RequestBody bodyBuilder = new FormBody.Builder()
.add("client_secret", CLIENT_SECRET)
.add("client_id", CLIENT_ID)
.add("code", AUTHORIZATION_CODE)
.add("grant_type", GRANT_TYPE)
.add("redirect_uri", REDIRECT_URI)
.build();
System.out.println("Built body: " + bodyBuilder.toString());
String mediaTypeString = "application/x-www-form-urlencoded";
MediaType mediaType = MediaType.parse(mediaTypeString);
RequestBody body = RequestBody.create(mediaType, requestbodyToString(bodyBuilder)); // See Edit 1
Request request = new Request.Builder()
.url(TARGET_URL)
.post(body)
.addHeader("content-type", mediaTypeString)
.addHeader("cache-control", "no-cache")
.build();
try {
System.out.println("Starting request.");
Response response = client.newCall(request).execute();
String targetUrl = request.url().toString() + bodyToString(request);
System.out.println("request: " + targetUrl);
String responseBodyString = response.body().string();
System.out.println("response: " + responseBodyString);
return responseBodyString;
} catch (IOException ex) {
System.out.println(ex);
}
Like I said, I keep getting a returned JSON of {"error":"invalid_client"}, and when I navigate to the URL I'm making the request to through a web browser it shows HTTP ERROR 405.
I'd love to provide as much additional information as you need. Thanks!
Edit 1: The second parameter of this used to be "bodyBuilder.toString()", but I changed it because I realized it wasn't actually sending the body. The result is still the same - {"error":"invalid_client"}. The method now used comes from here.
I figured out what it was - I hadn't actually been writing the authentication_code to the file, only adding it to another JSONObject. Oops. :)
I am trying to send url encoded data using HttpURLConnection method in java. Client shared the below string from Soap UI tester as a sample request:
http://www.clienturl.com/payment?username=bk&password=bk&customerid=100039085&amountcredit=100&operationdate=2018-07-17&event=9977773&reference=2323900&account=00000000&valuedate=2018-07-17&terminal=00010
I've tried all combinations of sending data using java. Am getting response code as 200, but the response is showing that missing mandatory parameters in the request. Please help if there are any error in my code, in writing the request.
StringBuffer response = new StringBuffer();
String EndPointURL = url;
String requestXML = "username=bk&password=bk&customerid=78233209438&amountcredit=100&operationdate=2018-07-17&event=9977773&reference=13903232&account=000000&valuedate=2018-07-17&terminal=00010";
String encodedData = URLEncoder.encode(requestXML, "UTF-8");
System.out.println("Encoded data: " + encodedData);
URL localURL = new URL(EndPointURL);
HttpURLConnection con = (HttpURLConnection) localURL.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Accept-Charset", charset);
con.setRequestProperty("Content-Length", Integer.toString(encodedData.length()));
OutputStream os = con.getOutputStream();
if you are using Okhttp3, use this code :
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "string-that-you-need-to-pass-in-body");
Request request = new Request.Builder()
.url("url-string")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.build();
Response response = client.newCall(request).execute();
For Unirest :
HttpResponse<String> response = Unirest.post("url-string")
.header("content-type", "application/x-www-form-urlencoded")
.body("string-that-you-need-to-pass-in-body")
.asString();