Java - 消息标头值中存在非法字符:基本

问题描述 投票:0回答:2

尝试使用 HttpUrlConnection 在 Java 中查询 api 时出现以下错误:

    "Exception in thread "main" java.lang.IllegalArgumentException: Illegal   character(s) in message header value: Basic MTk2YTVjODdhNWI2YjFmNWE3ZmQ5ODEtYjFjYTEzZmUtM2FkNC0xMWU1LWEyZjAtMDBkMGZlYTgy
NjI0OmY3NDQ2ZWQ0YjhjNzI2MzkyMzY1YzczLWIxY2ExNjQ4LTNhZDQtMTFlNS1hMmYwLTAwZDBm
ZWE4MjYyNA=="

这是我的代码:

public class LocalyticsTest {

        public static void main(String[] args) throws UnsupportedEncodingException {

            String apiKey = "MyKey";
            String apiSecret = "MySecretKey";
            String apiUrl = "https://api.localytics.com/v1/query";
            String credentials = apiKey + ":" + apiSecret;
            //String encoding = Base64.encode(apiKey.getBytes("UTF-8"));
            //String encoding2 = Base64.encode(apiSecret.getBytes("UTF-8"));
            String encoding3 = new sun.misc.BASE64Encoder().encode (credentials.getBytes("UTF-8"));

            String appId = "myAppId";
            String metric = "sessions";
            String dimensions = "day";
            String condition = "'{\"day\":[\"between\",\"'.$newDate.'\",\"'.$newDate.'\"]}'";
            Map data = new HashMap();
            data.put("app_id", appId);
            data.put("metric", metric);
            data.put("dimensions", dimensions);
            data.put("condition", condition);

            QueryEncoder q = new QueryEncoder();
            String newData = q.toQueryString(data);

            String newUrl = String.format("%s?%s", apiUrl, newData);


            try{
                URL url = new URL(newUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //conn.setRequestMethod("GET");
                //conn.setRequestProperty("Authorization", "Basic");
                //conn.setRequestProperty(apiKey,apiSecret);
                conn.setRequestProperty("Authorization", "Basic " + encoding3);
                conn.setRequestProperty("Accept", "application/vnd.localytics.v1+hal+json");


                if (conn.getResponseCode() != 200) {
                    throw new RuntimeException("Failed : HTTP error code : "
                            + conn.getResponseCode());
                }

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        (conn.getInputStream())));

                String output;
                System.out.println("Output from Server .... \n");
                while ((output = br.readLine()) != null) {
                    System.out.println(output);
                }

                conn.disconnect();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
       }
    }

我可以使用 Curl 使其在 php 中正常工作,如下所示:

function call_localytics_api($method, $url, $data)
{
    $curl = curl_init();
    $url = sprintf("%s?%s", $url, http_build_query($data));
    $api_key = "myKey";
    $api_secret = "mySecret";
    // Optional Authentication:
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($curl, CURLOPT_USERPWD, $api_key . ":" . $api_secret);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // Disable the SSL verificaiton process
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Accept: application/vnd.localytics.v1+hal+json"));

    // Confirm cURL gave a result, if not, write the error

    $response = curl_exec($curl);

    if ($response === FALSE) {
        die("Curl Failed: " . curl_error($curl));
    } else {
        return $response;
    }
}

$api_querystring = "https://api.localytics.com/v1/query";
$app_id = "myAppId";

$metric = "sessions";
$dimensions = "day";
//$data = array(app_id => $app_id, metrics => $metric, dimensions => $dimensions, conditions => '{"day":["in","'.$requestDate.'"]}');
$data = array(app_id => $app_id, metrics => $metric, dimensions => $dimensions, conditions => '{"day":["between","'.$newDate.'","'.$newDate.'"]}');
$response = call_localytics_api('GET', $api_querystring, $data);
$json = json_decode($response);
print_r($json);

只需要帮助让它在 Java 中工作。

java curl httpurlconnection
2个回答
11
投票

看来非法字符是换行符。 使用不会在结果中添加换行符的 Base 64 编码器,或者自行删除换行符。

从 Java 8 开始,您应该使用:

String encoding3 = Base64.getEncoder().encodeToString(
    credentials.getBytes(StandardCharsets.UTF_8));

在旧版本的 Java 中,您可以使用 DatatypeConverter:

String encoding3 = DatatypeConverter.printBase64Binary(
    credentials.getBytes(StandardCharsets.UTF_8));

您也可以直接删除换行符,但您应该使用上述方法之一。 sun.* 类不供开发使用,它们可能会从一个 Java 版本到下一版本发生更改或消失。 此外,据我了解,由于模块限制,从 Java 9 开始,无论它们是否存在,它们甚至可能根本无法使用。


0
投票

确保在编码为 Base64 时没有分块

org.apache.commons.net.util.Base64.encodeBase64String(texst.getBytes(), false);
© www.soinside.com 2019 - 2024. All rights reserved.