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();
Related
There is cookie header in my api request, every time I have to copy this cookie from postman and paste in my code to make it work. how can I generate cookie in my app and give that value in cookie header?
this is my login code:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("username","zee#earthonetechno.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=3e3710cb-9b41-47ea-ab1b-a1e1801e188b")
.build();
Response response = client.newCall(request).execute();
I want to put the cookie here in addHeader("Cookie", "session=3e3710cb-9b41-47ea-ab1b-a1e1801e188b")
I am developing in android studio
I found the solution for this
just include these lines in login part to get cookie
Headers allHeaders = response.headers();
headerValue = allHeaders.get("Set-Cookie");
and use this headerValue for subsequent api calls
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 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.
I have an api requirement of Sending following parameters in header-
Content-Type - application/x-www-form-urlencoded
authKey- (Session token)
and following parameters in body(form day i.e key-value pair)
storeId -1
type -Product
CategoryId -324
But whenever I hit this api, I am always getting 401(UnAuthorized) error.
I have tried using MultipartRequest body and formBody, I know this is nothing to do with the body(Its the header where I need to send the Content-Type and authKey). Below is my code-
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.addHeader("Content-Type", "application/x-www-form-urlencoded");
requestBuilder.addHeader("authKey",AppSharedPref.getTokenMobikul(context));
RequestBody formbody = new FormBody.Builder().add("CategoryId",bodyparms.get(0)).
add("type",bodyparms.get(1)).build();
requestBuilder.post(formbody);
The Same api is giving Response with retrofit library So how to achieve this using Okhttp.
Might this will help
FormBody.Builder formBuilder = new FormBody.Builder()
.add("key", "value");
// add more parameter as follow:
formBuilder.add("mobile", "9999999999");
RequestBody formBody = formBuilder.build();
Request request = new Request.Builder()
.url("https://www.hittheserver.com")
.post(formBody)
.build();
I am passing an authorization header with my Retrofit GET requests as documented by the Yelp Fusion documentation, which is shown below:
Authorization: Bearer MY_API_KEY
I am adding a network interceptor in my onCreate() method as shown below:
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
okHttpBuilder.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Authorization", "Bearer MY_API_KEY");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
//Yelp Client init
yelpRetrofit = new Retrofit.Builder()
.baseUrl("https://httpbin.org/")
.client(okHttpBuilder.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
yelpClient = yelpRetrofit.create(YelpClient.class);
Here is my YelpClient class :
public interface YelpClient {
#GET("headers")
Call<YelpJSON> searchTest(); }
This is the response I get when sending the request:
{"error": {"code": "TOKEN_MISSING", "description": "An access token must be supplied in order to use this endpoint."}}
I have successfully retrieved a response from the Yelp Fusion API with Postman and curl both using identical parameters and headers as my Retrofit request, so I can't blame Yelp. I have also attempted statically and dynamically setting the header with no success. Can anyone help me figure out what is wrong here?