簡體   English   中英

在 Java 中解碼 URI 查詢字符串

[英]Decoding URI query string in Java

我需要解碼包含查詢字符串的 URI; 預期的輸入/輸出行為類似於以下內容:

abstract class URIParser
{       
    /** example input: 
      * something?alias=pos&FirstName=Foo+A%26B%3DC&LastName=Bar */
    URIParser(String input) { ... }
    /** should return "something" for the example input */
    public String getPath(); 
    /** should return a map 
      * {alias: "pos", FirstName: "Foo+A&B=C", LastName: "Bar"} */
    public Map<String,String> getQuery();
}

我試過使用java.net.URI ,但它似乎對查詢字符串進行解碼,因此在上面的示例中,我只剩下 "alias=pos&FirstName=Foo+A&B=C&LastName=Bar" 所以是否存在歧義 "& " 是查詢分隔符或查詢組件中的字符。

編輯:我剛剛嘗試了URI.getRawQuery()並且它不進行編碼,所以我可以用&拆分查詢字符串,但是我該怎么辦? Javascript 有decodeURIComponent ,我好像在 Java 中找不到對應的方法。

有什么建議? 我不想使用任何新的庫。

URLDecoder.decode(proxyRequestParam.replace("+", "%2B"), "UTF-8")
          .replace("%2B", "+")

來模擬decodeURIComponent Java 的URLDecoder將加號解碼為空格,這不是您想要的,因此您需要替換語句。

警告:正如@xehpuk 指出的那樣,如果原始(pre-x-www-form-urlencoded)包含該字符串,則末尾的.replace("%2B", "+")破壞您的數據。

見類URLDecoder

var reqParam =  URLDecoder.decode(reqParam, "UTF-8")

關於 + 號的問題:

我根據@janb 的回答做了一個封裝了 URLDecoder 函數的輔助類

import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateDecoder {

    private static final String KEY_DATE = "datekey";

    private static final SimpleDateFormat SIMPLE_DATE_FORMAT =
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.US);


    public static void main(String[] args) throws UnsupportedEncodingException {
        try {
            Uri uri = Uri.parse("http://asdf.com?something=12345&" +
                    KEY_DATE +"=2016-12-24T12:00:00+01:00");

            System.out.println("parsed date: " + DateDecoder.createDate(uri)); // parsed date: Sat Dec 24 12:00:00 GMT+01:00 2016
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Nullable
    public static Date createDate(@Nullable Uri data) {
        if (data != null) {
            try {
                String withPlus = decodeButKeepPlus(KEY_DATE, data.getEncodedQuery());
                if (!TextUtils.isEmpty(withPlus)) {
                    return SIMPLE_DATE_FORMAT.parse(withPlus);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * copied from android.net.Uri.java
     */
    @Nullable
    public static String decodeButKeepPlus(String encodedKey, String completeEncodedQuery)
            throws UnsupportedEncodingException {

        final int length = completeEncodedQuery.length();
        int start = 0;
        do {
            int nextAmpersand = completeEncodedQuery.indexOf('&', start);
            int end = nextAmpersand != -1 ? nextAmpersand : length;

            int separator = completeEncodedQuery.indexOf('=', start);
            if (separator > end || separator == -1) {
                separator = end;
            }

            if (separator - start == encodedKey.length()
                    && completeEncodedQuery.regionMatches(start, encodedKey, 0, encodedKey.length())) {
                if (separator == end) {
                    return "";
                } else {
                    String encodedValue = completeEncodedQuery.substring(separator + 1, end);
                    if (!TextUtils.isEmpty(encodedValue)) {
                        return URLDecoder.decode(encodedValue.replace("+", "%2B"), "UTF-8").replace("%2B", "+");
                    }
                }
            }

            // Move start to end of name.
            if (nextAmpersand != -1) {
                start = nextAmpersand + 1;
            } else {
                break;
            }
        } while (true);
        return null;
    }

}
new java.net.URI(proxyRequestParam).getPath()

js encodeURIComponent 編碼的字符串應該只是一個路徑,沒有模式和其他東西。 然而,它仍然是 java.net.URI 的有效輸入。 所以 java.net.URI 會為我們做一切,然后它的路徑就是我們想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM