com.braintreepayments.http.serializer.FormEncoded Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of braintreehttp Show documentation
Show all versions of braintreehttp Show documentation
This is Braintree's generic http library for generated SDKs
package com.braintreepayments.http.serializer;
import com.braintreepayments.http.HttpRequest;
import com.braintreepayments.http.exceptions.SerializeException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
public class FormEncoded implements Serializer {
private static String safeRegex = "[A-Za-z]";
@Override
public String contentType() {
return "^application/x-www-form-urlencoded";
}
@Override
@SuppressWarnings("unchecked")
public byte[] encode(HttpRequest request) throws IOException {
if (!(request.requestBody() instanceof Map)) {
throw new SerializeException("Request requestBody must be Map when Content-Type is application/x-www-form-urlencoded");
}
Map body = (Map) request.requestBody();
List parts = new ArrayList<>(body.size());
for (String key : body.keySet()) {
parts.add(key + "=" + urlEscape(body.get(key)));
}
return String.join("&", parts).getBytes();
}
@Override
public T decode(String source, Class cls) throws IOException {
throw new UnsupportedEncodingException("Unable to decode Content-Type: " + contentType());
}
public static String urlEscape(String input) {
StringBuilder res = new StringBuilder();
char[] charArray = input.toCharArray();
String currentChar = "";
for (int i = 0; i < charArray.length; i ++) {
char c = charArray[i];
currentChar = (currentChar + c).substring(i > 0 ? 1 : 0);
if (!currentChar.matches(safeRegex)) {
res.append('%');
res.append(toHex(c / 16));
res.append(toHex(c % 16));
} else {
res.append(c);
}
}
return res.toString();
}
private static char toHex(int ch) {
return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
}
}