I need your help, i'd like to know if there is a way to post a FormDataMultiPart with okHttp.
I know you're gonna say that there already are responses.
This is my case :
// Resource
#Consume(FORMDATAMULTIPART)
public Response getMultiPart(FormDataMultiPart multipart) {
return response.ok(service.postMultiPart(multipart);
}
// Service
public void postMultiPart(FormDataMultiPart multiPart) {
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder() {
.url(URL)
.post(multiPart)
}
I know that post only get RequestBody and this is my question, do you know guys a way to convert the FormDataMultiPart to RequestBody??
Thanks a lot
In the Service change this part of the code
final Request request = new Request.Builder() {
.url(URL)
.post(multiPart)
to (assuming i'm sending a file) and use RequestBuilder
File file; // This is the file I want to send.
MediaType mediaType = MediaType.parse("multipart/form-data");
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("key", "name", RequestBody.create(mediaType, file)).build();
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder()
.headers(headerBuild)
.url(url);
requestBuilder.post(requestBody);
okhttp3.Request request = requestBuilder.build();
Have a look at MediaType which has been added in the above code.
Related
How can I pass parameter with "--data {json}" on okHttp3? Do I need to add it in the headers like below? Or its not on the header, it need to be on another object?
Request request = new Request.Builder()
.header("Content-Type", "application/json; charset=utf-8")
.addHeader("data", "{json}")
.url(url)
Please let me know.
You must add to RequestBody :
final String BOUNDARY = String.valueOf(System.currentTimeMillis());
RequestBody requestBody = new MultipartBody.Builder(BOUNDARY)
.setType(MultipartBody.FORM)
.addFormDataPart("data", JsonData)
//.addFormDataPart("otherPara", otherPara)
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
I am using an API which uploads some data to the server, I am deploying this on android application.
I tested APIs using Postman and it works absolutely fine and generated code from postman
login code:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("username","abc#abc.com")
.addFormDataPart("password","E1234567")
.build();
Request request = new Request.Builder()
.url("192.168.1.51/auth/login")
.method("POST", body)
.addHeader("User-Agent", "Koala Admin")
.addHeader("Content-Type", "application/json")
.addHeader("Cookie", "session=3d9c1888-e9b0-40b3-958b-71c50538d338")
.build();
Response response = client.newCall(request).execute();
create user and upload photo
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("subject_type","1")
.addFormDataPart("name","jasim")
.addFormDataPart("start_time","1619496549")
.addFormDataPart("end_time","1619525349")
.addFormDataPart("photo","/C:/Users/jasim/Pictures/Camera Roll/WIN_20210422_14_54_39_Pro.jpg",
RequestBody.create(MediaType.parse("application/octet-stream"),
new File("/C:/Users/jasim/Pictures/Camera Roll/WIN_20210422_14_54_39_Pro.jpg")))
.build();
Request request = new Request.Builder()
.url("192.168.1.51/subject/file")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Cookie", "session=3d9c1888-e9b0-40b3-958b-71c50538d338")
.build();
Response response = client.newCall(request).execute();
Now I want to know that how can I put these code in AsyncTask class and make the necessary code in background.
You can call enqueue method instead of execute and it will work on the background thread:
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) throws IOException {
// handle your response
}
#Override
public void onFailure(Call call, IOException e) {
// handle the failure
}
});
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();
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 need to write a middleware for OKHttp to intercept all sended query parameters (key1=value1&key2=value2&...) and generate a digest according to the parameters and then put it on a specific header and send it along with the request, I can intercept all request through the following way:
OkHttpClient httpClient = new OkHttpClient();
httpClient.interceptors().add(new Interceptor() {
#Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
String digest = "How can I get sended paramters?";
Request request = original.newBuilder()
.header("User-Agent", "Your-App-Name")
.header("Digest", digest)
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
But I can't find a way to retrieve the list of parameters! any ideas?
It's been a while, but I believe you can just do:
Request original = chain.request();
String params = original.url().query();
don't have an android environment to test this with at the moment though. If not look at the okhttp javadoc for Request and HttpUrl
EDIT
for the post body there's a question here which I think does what you're after, but in a nutshell it's something like:
Request original = chain.request();
Buffer buffer = new Buffer();
original.body().writeTo(buffer);
String bodyStr = buffer.readUtf8();