Opening the connection using okhttp - android

I'm trying to Open the connection using okhttp.
something like,
urlConnection = client.open(url);
does not work with the new ok-http.jar file.
It was working with 1.5.x of okhttp version
Any suggestions?
Thanks

Code from documentation
public static void main(String[] args) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://kenumir.pl/")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
Method execute is the key ;-)

What does it means "it does not work"??? Does it fails at compile time or runtime? What kind of error does it shows? As of OkHttip 2.x.x, there's been a change in the way to open HttpUrlConnections, you need to include a new module and this should work:
// OkHttp 1.x:
HttpURLConnection connection = client.open(url);
// OkHttp 2.x:
HttpURLConnection connection = new OkUrlFactory(client).open(url);
see OkHttp Release notes for more information .

Related

How to get references of variables in APK?

I'm doing the static analysis on Android APK file. Given the following source code:
protected void OkHttpClientCheck() throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.vogella.com/index.html")
.build();
Response response = client.newCall(request).execute();
}
So I can extract this source code uses OkHttpClient to open a connection and the target URL by using pattern matching (likes grep with regex). My question is, how do we map the OkHttpClient API with the corresponding url? In other words, I would like to output: "https://www.vogella.com/index.html" is called by OkHttpClient.
Can androguard do it or I need to perform static analysis with Soot or Flowdroid?
I have tried androguard but it could not extract the detail inside a method. Is it true or did I miss something?

OkHttp MockWebServer with dynamic URLs using Retrofit

My app uses dynamic URLs to make web-service calls (on Android). baseUrl is set as empty and we pass Retrofit2 #Url parameters in the service interface:
public interface UserService {
#GET
public Call<ResponseBody> profilePicture(#Url String url);
}
We don't know the host/domain in advance, so MockWebServer is not able to intercept the requests. The call to fetch the initial list of dynamic URLs is made in different screens. One idea is to create a new flavor providing a local data source for URLs to be used, which is my fallback plan.
I am curious if MockWebServer has any other methods to help test such cases and can be limited to test code.
You could use an OkHttp interceptor to rewrite the hostname and port?
I was also facing the same kind of issue. When I use MockWebserver in testing I have to change base URL to target mock web server localhost and port. I tried this it is working fine.
private static final Interceptor mRequestInterceptor = new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
final InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 8080);
HttpUrl httpUrl = request.url().newBuilder().scheme("http://").host(address.getHostName()).port(8080)
.build();
request = request.newBuilder()
.url(httpUrl)
.build();
return chain.proceed(request);
}
};
After this base url changes to "http://localhost:8080/"

Correct syntax for adding parameters to get() and post() request using okhttp in Android

What I want to achieve ?
I am trying to send two parameters in my Server URL using OkHttp through both get and post bcoz i want to know the syntax for both the methods.
What I had Tried ?
I have searched SO for questions on OkHttp but those had not solved my IllegalArgumentException.
I have seen below links :
Add query params to a GET request in okhttp in Android
and this
How to add parameters to api (http post) using okhttp library in Android
and
How to add query parameters to a HTTP GET request by OkHttp?
Exception from code 2:
Code I had used till now :
1)GET
urls = chain.request().httpUrl() <-- NullPointerException Line
.newBuilder()
.scheme("http")
.host(SERVER_IP)
.addQueryParameter("from", valueFrom)
.addQueryParameter("to",valueTo)
.build();
request = chain.request().newBuilder().url(urls).build();
response = chain.proceed(request);
2)GET
urls =new HttpUrl.Builder()
.host(SERVER_IP) <--- IllegalArgumentException line
.addQueryParameter("from", valueFrom)
.addQueryParameter("to", valueTo)
.build();
request = new Request.Builder().url(urls).build();
response = client.newCall(request).execute();
3)POST
body = new
MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("from",
valueFrom).addFormDataPart("to",valueTo).build();
Log.i("Body data",""+body.toString());
request = new Request.Builder().url(params[0]).post(body).build();
Log.i("Request data",""+request.toString());
response = client.newCall(request).execute();
4)POST
body = new FormEncodingBuilder().add("from", valueFrom).add("to",
valueTo).build();
Log.i("Body data",""+body.toString());
request = new Request.Builder().url(params[0]).post(body).build();
Log.i("Request data",""+request.toString());
response = client.newCall(request).execute();
build.gradle
dependencies
{
compile files('libs/okhttp-2.5.0.jar')
compile files('libs/okio-1.6.0.jar')
}
Thanks In Advance...
Edit :
The above code for POST request is working fine now
But for GET request I still have no solution.
Just set your GET parameter extend your URL:
RequestBody body = new FormEncodingBuilder()
.add("requestParamName", requestParameter.getRequestParams())
.build();
Request request = new Request.Builder()
.url("https://www.test.com/serviceTest?parama=abc&paramb=123")
.post(body)
.build();

How to use http/2 with Okhttp on Android devices?

I'M testing a site that supports HTTP/2,like this,
and I try to use okhttp to send the request:
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.google.it")
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
Log.d("TestHttp", "OkHttp-Selected-Protocol: " + response.header("OkHttp-Selected-Protocol"));
Log.d("TestHttp", "Response code is " + response.code());
}
});
In the log I got something like this:
OkHttp-Selected-Protocol: http/1.1
The okhttpClient chose to use http/1.1, how can I force it to use HTTP/2?
Okhttp 2.5+ only support http/2 above 5.0+ via ALPN.
but you can modify the source code to support http/2 above 4.0+ via NPN.
You just need to initialize your OkHttpClient in proper way.
Kotlin:
val client = OkHttpClient().newBuilder()
.protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))
.build()
// Your client will now try to use HTTP 2 if possible. If not, then HTTP 1.1 will be used.
Java:
List<Protocol> protocols = new ArrayList<Protocol>();
protocols.add(Protocol.HTTP_2);
protocols.add(Protocol.HTTP_1_1);
OkHttpClient client = new OkHttpClient.Builder()
.protocols(protocols)
.build();
// Your client will now try to use HTTP 2 if possible. If not, then HTTP 1.1 will be used.
If you wish to check if HTTP 2 is being used, see my other answer: https://stackoverflow.com/a/72983159/1735603

Get redirected URL from Picasso

I'm fetching my images using the following code:
Picasso.with(mContext)
.load(myImage.getUrl())
.fetch();
myImage.getUrl() returns a URL from my server, which will redirect to the actual image hosted on another server. Is there a way to catch the URL my server returns to Picasso? I know I can use a Callback in .fetch(), but that's all I know. I'm using OkHttp as well.
OkHttp allows you not to follow redirects automatically:
OkHttpClient client = new OkHttpClient();
client.setFollowRedirects(false);
You can read the response, get the redirect URL and then forward it manually to Picasso.
EDIT:
Interceptors are feasible as well:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
// process response here
return response;
}
});
I fixed it by this code.
val downloader = OkHttp3Downloader(context)
Picasso.Builder(context).downloader(downloader).build()
Check this for detail.
https://github.com/square/picasso/issues/463
Add okhttp dependency
compile 'com.squareup.okhttp:okhttp:2.5.0'
and try this code
Picasso.Builder builder = new Picasso.Builder(context);
builder.downloader(new OkHttpDownloader(context));
builder.build()
.load(path.trim())
.into(imageView);
This code working for me

Categories

Resources