All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.braintreepayments.http.serializer.FormEncoded Maven / Gradle / Ivy

There is a newer version: 1.3.1
Show newest version
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);
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy