package io.netty.handler.codec.http;

import io.netty.util.internal.ObjectUtil;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

/* JADX INFO: loaded from: classes.dex */
public class QueryStringEncoder {
    private final String charsetName;
    private boolean hasParams;
    private final StringBuilder uriBuilder;

    public QueryStringEncoder(String str) {
        this(str, HttpConstants.DEFAULT_CHARSET);
    }

    public QueryStringEncoder(String str, Charset charset) {
        this.uriBuilder = new StringBuilder(str);
        this.charsetName = charset.name();
    }

    private static void appendComponent(String str, String str2, StringBuilder sb) {
        try {
            String strEncode = URLEncoder.encode(str, str2);
            int iIndexOf = strEncode.indexOf(43);
            if (iIndexOf == -1) {
                sb.append(strEncode);
                return;
            }
            sb.append((CharSequence) strEncode, 0, iIndexOf);
            sb.append("%20");
            int length = strEncode.length();
            while (true) {
                iIndexOf++;
                if (iIndexOf >= length) {
                    return;
                }
                char cCharAt = strEncode.charAt(iIndexOf);
                if (cCharAt != '+') {
                    sb.append(cCharAt);
                } else {
                    sb.append("%20");
                }
            }
        } catch (UnsupportedEncodingException unused) {
            throw new UnsupportedCharsetException(str2);
        }
    }

    public void addParam(String str, String str2) {
        ObjectUtil.checkNotNull(str, "name");
        if (this.hasParams) {
            this.uriBuilder.append('&');
        } else {
            this.uriBuilder.append('?');
            this.hasParams = true;
        }
        appendComponent(str, this.charsetName, this.uriBuilder);
        if (str2 != null) {
            this.uriBuilder.append('=');
            appendComponent(str2, this.charsetName, this.uriBuilder);
        }
    }

    public String toString() {
        return this.uriBuilder.toString();
    }

    public URI toUri() {
        return new URI(toString());
    }
}
