在Youtube HTTP请求中指定空格字符

时间:2015-11-29 09:54:23

标签: java http youtube youtube-data-api

以下是我向Youtube发出HTTP数据请求的代码:

 String apiKey =MY_KEY;
//variable input contains search keyword
    String query = "";
    if(input.contains(" "))
        query = "https://www.googleapis.com/youtube/v3/search?part=snippet&q="+input.replace(" ","+")+"&type=video&videoCaption=closedCaption&key="+apiKey;
    else
        query = "https://www.googleapis.com/youtube/v3/search?part=snippet&q="+input+"&type=video&videoCaption=closedCaption&key="+apiKey;
    try {
        response = makeHTTPRequest.sendGet(query);
    }
    catch (Exception e){
        e.printStackTrace();
    }

    System.out.println("Youtube results : "+response);

所以我试图用 + 符号替换关键字中的空格字符,例如电子城。这是错的吗?应该为电子城而不只是电子城市获取搜索结果需要做哪些更改?

目前,我还获得了电子城和电子产品的搜索结果。

1 个答案:

答案 0 :(得分:2)

您需要url encode个特定字符。幸运的是,你可以使用URLEncoder来做类似的事情,

try {
    String query = String.format("https://www.googleapis.com/" //
                + "youtube/v3/search?part=snippet&q=%s&type=video&" //
                + "videoCaption=closedCaption&key=%s", URLEncoder.encode( //
            input, "UTF-8"), URLEncoder.encode(apiKey, "UTF-8"));
    response = makeHTTPRequest.sendGet(query);
    System.out.printf("Youtube results : %s%n", response);
} catch (Exception e) {
    e.printStackTrace();
}