Last active
February 3, 2018 18:14
-
-
Save chibatching/a59e30def6956da04b2f to your computer and use it in GitHub Desktop.
OAuth signed POST request with Volley + oauth-signpost
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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the implementation
mOauthSignedPosts.contains(url) fails. Needs to convert to string. mOauthSignedPosts.contains(url.toString()) works.