Skip to content

Instantly share code, notes, and snippets.

@chibatching
Last active February 3, 2018 18:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chibatching/a59e30def6956da04b2f to your computer and use it in GitHub Desktop.
Save chibatching/a59e30def6956da04b2f to your computer and use it in GitHub Desktop.
OAuth signed POST request with Volley + oauth-signpost
public class OAuthPostHurlStack extends HurlStack {
private final OAuthConsumer mConsumer;
private ArrayList<String> mOauthSignedPosts = new ArrayList<>();
public OAuthPostHurlStack(OAuthConsumer consumer) {
mConsumer = consumer;
}
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
if (request.getMethod() == Request.Method.POST) {
if (request instanceof CustomRequest) {
// Flag for OAuth POST request
mOauthSignedPosts.add(request.getUrl());
// Make OAuth parameters with POST parameters
HttpParameters oauthParams = new HttpParameters();
Map<String, String> params = ((CustomRequest) request).getParams();
for (String key : params.keySet()) {
oauthParams.put(key, OAuth.percentEncode(params.get(key)));
}
// Add end point url for OAuth params
oauthParams.put("realm", request.getUrl());
// Set params to consumer
mConsumer.setAdditionalParameters(oauthParams);
}
}
return super.performRequest(request, additionalHeaders);
}
@Override
protected HttpURLConnection createConnection(URL url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
if (mOauthSignedPosts.contains(url)) {
// If the post request needs OAuth signing,
// set method "POST" and DoOutput true.
connection.setRequestMethod("POST");
connection.setDoOutput(true);
mOauthSignedPosts.remove(url);
}
mConsumer.sign(connection);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
return connection;
}
}
@santoshmehta82
Copy link

Thanks for the implementation

mOauthSignedPosts.contains(url) fails. Needs to convert to string. mOauthSignedPosts.contains(url.toString()) works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment