Last active
July 24, 2023 08:53
-
-
Save elroid/b2137899f72c09d0b07aa8e3ede58499 to your computer and use it in GitHub Desktop.
BranchRemoteInterface using OkHttp3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json.JSONObject; | |
import java.io.IOException; | |
import io.branch.referral.network.BranchRemoteInterface; | |
import okhttp3.MediaType; | |
import okhttp3.OkHttpClient; | |
import okhttp3.Request; | |
import okhttp3.RequestBody; | |
import okhttp3.Response; | |
import okhttp3.ResponseBody; | |
import timber.log.Timber; | |
import static io.branch.referral.BranchError.ERR_BRANCH_UNABLE_TO_REACH_SERVERS; | |
public class BranchNetworkClient extends BranchRemoteInterface | |
{ | |
@Override | |
public BranchResponse doRestfulGet(String url) throws BranchRemoteException{ | |
Timber.d("doRestfulGet(url:%s)", url); | |
try{ | |
OkHttpClient client = new OkHttpClient(); | |
Request request = new Request.Builder().url(url).build(); | |
Response response = client.newCall(request).execute(); | |
return new BranchResponse(body(response), response.code()); | |
} | |
catch(Exception e){ | |
Timber.e(e, "Error in doRestfulGet("+url+")"); | |
throw new BranchRemoteException(ERR_BRANCH_UNABLE_TO_REACH_SERVERS); | |
} | |
} | |
@Override | |
public BranchResponse doRestfulPost(String url, JSONObject payload) throws BranchRemoteException{ | |
Timber.d("doRestfulPost(url:%s, payload:%s)", url, payload); | |
try{ | |
MediaType JSON = MediaType.parse("application/json; charset=utf-8"); | |
OkHttpClient client = new OkHttpClient(); | |
RequestBody body = RequestBody.create(JSON, payload.toString()); | |
Request request = new Request.Builder().url(url).post(body).build(); | |
Response response = client.newCall(request).execute(); | |
return new BranchResponse(body(response), response.code()); | |
} | |
catch(Exception e){ | |
Timber.e(e, "Error in doRestfulGet("+url+")"); | |
throw new BranchRemoteException(ERR_BRANCH_UNABLE_TO_REACH_SERVERS); | |
} | |
} | |
private String body(Response response) throws IOException{ | |
String result = "No data"; | |
if(response == null) return result; | |
ResponseBody body; | |
if((body = response.body()) == null) | |
return result; | |
else | |
return body.string(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment