Skip to content

Instantly share code, notes, and snippets.

@akshaydashrath
Last active March 25, 2024 13:54
Show Gist options
  • Save akshaydashrath/10119943 to your computer and use it in GitHub Desktop.
Save akshaydashrath/10119943 to your computer and use it in GitHub Desktop.
Signing HttpUrlConnection using OkHttpClient and Retrofit
@Override
public Response execute(Request request) throws IOException {
HttpsURLConnection connection = (HttpsURLConnection) super.openConnection(request);
try {
prepareRequest(connection, request);
} catch (Exception e) {
e.printStackTrace();
}
return readResponse(connection);
}
void prepareRequest(HttpURLConnection connection, Request request)
throws IOException, OAuthExpectationFailedException, NoSuchAlgorithmException,
OAuthCommunicationException, OAuthMessageSignerException {
if (Build.VERSION.SDK_INT > 13) {
connection.setRequestProperty("Connection", "close");
}
connection.setRequestMethod(request.getMethod());
connection.setDoInput(true);
for (Header header : request.getHeaders()) {
connection.addRequestProperty(header.getName(), header.getValue());
}
TypedOutput body = request.getBody();
long length = -1;
if (body != null) {
connection.setDoOutput(true);
length = body.length();
}
RequestSigner.create(CONSUMER_KEY, CONSUMER_SECRET)
.setOAuthTokenAndSecret(getToken(request), getoAuthSecret(request))
.sign(request, connection);
if (length != -1) {
connection.setFixedLengthStreamingMode((int) length);
} else {
connection.setChunkedStreamingMode(CHUNK_SIZE);
}
if (body!=null) {
body.writeTo( connection.getOutputStream() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment