2015-11-29 52 views
1

這裏是我的代碼,以使一個HTTP數據請求到Youtube:指定空格字符

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); 

所以我想在某個關鍵字代替空格字符,例如電子城 +標誌。這是錯的嗎?什麼樣的變化,應使僅獲取電子城的搜索結果,而不是隻是電子城市

目前我正在搜索電子城以及電子產品的搜索結果。

回答

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(); 
}