Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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;
}
}

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