@Test public void testGetWithRequestBuilder() throws UnsupportedEncodingException { ConsumerKey consumer = new ConsumerKey(CONSUMER_KEY, CONSUMER_SECRET); RequestToken user = new RequestToken(TOKEN_KEY, TOKEN_SECRET); OAuthSignatureCalculator calc = new StaticOAuthSignatureCalculator(consumer, user, TIMESTAMP, NONCE); final Request req = get("http://photos.example.net/photos") // .addQueryParam("file", "vacation.jpg") // .addQueryParam("size", "original") // .setSignatureCalculator(calc) // .build(); final List<Param> params = req.getQueryParams(); assertEquals(params.size(), 2); // From the signature tester, the URL should look like: // normalized parameters: // file=vacation.jpg&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_nonce=kllo9940pd9333jh&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1191242096&oauth_token=nnch734d00sl2jdk&oauth_version=1.0&size=original // signature base string: // GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal // signature: tR3+Ty81lMeYAr/Fid0kMTYa/WM= // Authorization header: OAuth // realm="",oauth_version="1.0",oauth_consumer_key="dpf43f3p2l4k3l03",oauth_token="nnch734d00sl2jdk",oauth_timestamp="1191242096",oauth_nonce="kllo9940pd9333jh",oauth_signature_method="HMAC-SHA1",oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D" String authHeader = req.getHeaders().get(AUTHORIZATION); Matcher m = Pattern.compile("oauth_signature=\"(.+?)\"").matcher(authHeader); assertEquals(m.find(), true); String encodedSig = m.group(1); String sig = URLDecoder.decode(encodedSig, "UTF-8"); assertEquals(sig, "tR3+Ty81lMeYAr/Fid0kMTYa/WM="); assertEquals(req.getUrl(), "http://photos.example.net/photos?file=vacation.jpg&size=original"); }
private static void addQueryString(final Request request, final HttpRequestPacket requestPacket) { final FluentStringsMap map = request.getQueryParams(); if (isNonEmpty(map)) { StringBuilder sb = new StringBuilder(128); for (final Map.Entry<String, List<String>> entry : map.entrySet()) { final String name = entry.getKey(); final List<String> values = entry.getValue(); if (isNonEmpty(values)) { try { for (int i = 0, len = values.size(); i < len; i++) { final String value = values.get(i); if (isNonEmpty(value)) { sb.append(URLEncoder.encode(name, "UTF-8")) .append('=') .append(URLEncoder.encode(values.get(i), "UTF-8")) .append('&'); } else { sb.append(URLEncoder.encode(name, "UTF-8")).append('&'); } } } catch (UnsupportedEncodingException ignored) { } } } sb.setLength(sb.length() - 1); String queryString = sb.toString(); requestPacket.setQueryString(queryString); } }