解决方案电影标题中丢失代码的片段,完成更多挑战

时间:2018-01-25 17:10:15

标签: java json http

要解决此挑战,请编写HTTP GET方法以从特定电影数据库中检索信息。在编辑器中完成该功能;它有一个参数:一个字符串,substr。该功能必须执行以下任务:

  1. 查询https://jsonmock.hackerrank.com/api/movies/search/?Title=substr(其中substr是substr的值)。来自网站的查询响应是JSON响应,包含以下五个字段:
  2. •page:当前页面。

    •per_page:每页的最大结果数。

    •total:此标题中包含子字符串substr的电影总数。

    •total_pages:必须查询以获取所有结果的总页数。

    •data:包含电影信息的JSON对象数组,其中Title字段表示电影的标题。请注意,此字段是分页的,因此,为了合并分页,您必须查询https://jsonmock.hackerrank.com/api/movies/search/?Title=substr&page=pageNumber,其中pageNumber是一个整数,表示您要查看的页面(例如,1,2等)。

    1. 创建一个名为titles的字符串数组来存储总元素。对于每个结果页面,将每个电影的标题存储在标题数组中。

    2. 按升序排序标题并将其作为答案返回。

    3. 输入格式

      单个字符串substr,表示您必须查询的子字符串。

      输出格式

      返回与标题相对应的字符串数组,其标题为susbtr,按升序排序。

      示例输入0

      蜘蛛侠

      示例输出0

      • 惊人的蜘蛛侠综合症
      • 战斗,飞行和驾驶:蜘蛛侠3的特技
      • 好莱坞大师讲故事:蜘蛛侠直播
      • 意大利蜘蛛侠
      • 蜘蛛侠
      • 蜘蛛侠
      • 蜘蛛侠5
      • 蜘蛛侠和奶奶
      • 戛纳的蜘蛛侠
      • 超人,蜘蛛侠或蝙蝠侠
      • The Amazing Spiderman T4 Premiere Special
      • 蜘蛛侠之死
      • 他们叫我蜘蛛侠

      解释0

      对于此示例,我们希望所有包含子串spiderman的电影标题。查询https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=1的响应是:

      { 
        "page": "1",
        "per_page": 10,
        "total": 13,
        "total_pages": 2,
        "data": [
      {
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BYjFhN2RjZTctMzA2Ni00NzE2LWJmYjMtNDAyYTllOTkyMmY3XkEyXkFqcGdeQXVyNTA0OTU0OTQ@._V1_SX300.jpg",
        "Title": "Italian Spiderman",
        "Type": "movie",
        "Year": "2007",
        "imdbID": "tt2705436"
      },
      {
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BMjQ4MzcxNDU3N15BMl5BanBnXkFtZTgwOTE1MzMxNzE@._V1_SX300.jpg",
        "Title": "Superman, Spiderman or Batman",
        "Type": "movie",
        "Year": "2011",
        "imdbID": "tt2084949"
      },
      {
        "Poster": "N/A",
        "Title": "Spiderman",
        "Type": "movie",
        "Year": "1990",
        "imdbID": "tt0100669"
      },
      {
        "Poster": "N/A",
        "Title": "Spiderman",
        "Type": "movie",
        "Year": "2010",
        "imdbID": "tt1785572"
      },
      {
        "Poster": "N/A",
        "Title": "Fighting, Flying and Driving: The Stunts of Spiderman 3",
        "Type": "movie",
        "Year": "2007",
        "imdbID": "tt1132238"
      },
      {
        "Poster": "http://ia.media-imdb.com/images/M/MV5BMjE3Mzg0MjAxMl5BMl5BanBnXkFtZTcwNjIyODg5Mg@@._V1_SX300.jpg",
        "Title": "Spiderman and Grandma",
        "Type": "movie",
        "Year": "2009",
        "imdbID": "tt1433184"
      },
      {
        "Poster": "N/A",
        "Title": "The Amazing Spiderman T4 Premiere Special",
        "Type": "movie",
        "Year": "2012",
        "imdbID": "tt2233044"
      },
      {
        "Poster": "N/A",
        "Title": "Amazing Spiderman Syndrome",
        "Type": "movie",
        "Year": "2012",
        "imdbID": "tt2586634"
      },
      {
        "Poster": "N/A",
        "Title": "Hollywood's Master Storytellers: Spiderman Live",
        "Type": "movie",
        "Year": "2006",
        "imdbID": "tt2158533"
      },
      {
        "Poster": "N/A",
        "Title": "Spiderman 5",
        "Type": "movie",
        "Year": "2008",
        "imdbID": "tt3696826"
      }]}
      

      查询https://jsonmock.hackerrank.com/api/movies/search/?Title=spiderman&page=2的响应是:

      {
        "page": "2",
        "per_page": 10,
        "total": 13,
        "total_pages": 2,
        "data": [
      {
        "Poster": "N/A",
        "Title": "They Call Me Spiderman",
        "Type": "movie",
        "Year": "2016",
        "imdbID": "tt5861236"
      },
      {
        "Poster": "N/A",
        "Title": "The Death of Spiderman",
        "Type": "movie",
        "Year": "2015",
        "imdbID": "tt5921428"
      },
      {
        "Poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BZDlmMGQwYmItNTNmOS00OTNkLTkxNTYtNDM3ZWVlMWUyZDIzXkEyXkFqcGdeQXVyMTA5Mzk5Mw@@._V1_SX300.jpg",
        "Title": "Spiderman in Cannes",
        "Type": "movie",
        "Year": "2016",
        "imdbID": "tt5978586"
      }]}
      

      每个响应页面中每部电影的标题字段的相应值为:

      • 意大利蜘蛛侠
      • 超人,蜘蛛侠或蝙蝠侠
      • 蜘蛛侠
      • 蜘蛛侠
      • 战斗,飞行和驾驶:蜘蛛侠3的特技
      • 蜘蛛侠和奶奶
      • The Amazing Spiderman T4 Premiere Special
      • 惊人的蜘蛛侠综合症
      • 好莱坞大师讲故事:蜘蛛侠直播
      • 蜘蛛侠5
      • 他们叫我蜘蛛侠
      • 蜘蛛侠之死
      • 戛纳的蜘蛛侠

      然后我们将每个标题存储在titles数组中,按升序排序,并将其作为我们的答案返回。

      import java.io.*;
      import java.util.*;
      import java.text.*;
      import java.math.*;
      import java.util.regex.*;
      import java.net.*;
      import com.google.gson.*;
      
      public class Solution {
      /*
       * Complete the function below.
       */
      
      static String[] getMovieTitles(String substr) {
      
            //complete function here
      }
      
      
      public static void main(String[] args) throws IOException{
          Scanner in = new Scanner(System.in);
          final String fileName = System.getenv("OUTPUT_PATH");
          BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
          String[] res;
          String _substr;
          try {
              _substr = in.nextLine();
          } catch (Exception e) {
              _substr = null;
          }
      
          res = getMovieTitles(_substr);
          for(int res_i=0; res_i < res.length; res_i++) {
              bw.write(String.valueOf(res[res_i]));
              bw.newLine();
          }
      
          bw.close();
          } 
      }
      

11 个答案:

答案 0 :(得分:4)

这是一个Javascript答案。

&#13;
&#13;
var https = require('https');

function fetchData(substr) {
    pageNum = 1;
    let url = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + pageNum;
    https.get(url, (res) => {
        res.setEncoding('utf8');
        res.on('data', function(body) {
            let dataRec = JSON.parse(body);
            let movies = dataRec.data;
            let totPages = dataRec.total_pages;
            let sortArray = [];
            movies.map((a) => {
              sortArray.push(a.Title)
            })
            for (let i = 2; i <= totPages; i++) {
                let newPage = i;
                let url1 = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + substr + "&page=" + newPage;
                https.get(url1, (res) => {
                    res.setEncoding('utf8');
                    res.on('data', function(body) {
                        let newData = JSON.parse(body);
                        let newMovies = newData.data;
                        for (let i = 0; i < newMovies.length; i++) {
                            sortArray.push(newMovies[i].Title);
                        }
                        console.log(sortArray.sort());
                    })
                })
            }
        })
    })
}

//primary function 
function getMovieTitles(substr) {
    fetchData(substr);
}

getMovieTitles("spiderman");
&#13;
&#13;
&#13;

答案 1 :(得分:2)

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * 
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class MovieTitle {

    @JsonProperty("Poster")
    private String poster;

    @JsonProperty("Title")
    private String title;

    @JsonProperty("Type")
    private String type;

    @JsonProperty("Year")
    private String year;

    @JsonProperty("imdbID")
    private String imdbID;

    public String getPoster() {
        return poster;
    }

    public void setPoster(String poster) {
        this.poster = poster;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getImdbID() {
        return imdbID;
    }

    public void setImdbID(String imdbID) {
        this.imdbID = imdbID;
    }

}


import java.util.List;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * @author
 *
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class SearchResult {

    @JsonProperty("page")
    private String page;

    @JsonProperty("per_page")
    private String per_page;

    @JsonProperty("total")
    private String total;

    @JsonProperty("total_pages")
    private String total_pages;

    @JsonProperty("data")
    private List<MovieTitle> movieTitles;

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    public String getPer_page() {
        return per_page;
    }

    public void setPer_page(String per_page) {
        this.per_page = per_page;
    }

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public String getTotal_pages() {
        return total_pages;
    }

    public void setTotal_pages(String total_pages) {
        this.total_pages = total_pages;
    }

    public List<MovieTitle> getMovieTitles() {
        return movieTitles;
    }

    public void setMovieTitles(List<MovieTitle> movieTitles) {
        this.movieTitles = movieTitles;
    }

}

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import com.rest.model.SearchResult;

/**
 * @author
 *
 */
public class SprngRestClient {

    public static void main(String args[]) {
        getMovieTitles("spiderman");
    }

    static void getMovieTitles(String movietitle) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("sample.proxy", 8080));
        requestFactory.setProxy(proxy);
        List<String> moviewTitles = new ArrayList<String>();
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        int pageNo = 0;
        int totalPages = 100000;
        while (pageNo != totalPages) {
            pageNo = pageNo + 1;
            SearchResult quote = restTemplate.getForObject(
                    "https://jsonmock.hackerrank.com/api/movies/search/?Title=" + movietitle + "&page=" + pageNo,
                    SearchResult.class);
            moviewTitles.addAll(quote.getMovieTitles()
                                     .stream()
                                     .map(title -> title.getTitle())
                                     .collect(Collectors.toList()));
            pageNo = Integer.parseInt(quote.getPage());
            totalPages = Integer.parseInt(quote.getTotal_pages());
        }
        moviewTitles.sort((name1, name2) -> name1.compareTo(name2));
        moviewTitles.forEach(System.out::println);
    }

}

答案 2 :(得分:2)

这是您要寻找的:

String[] getMovieTitles(String substr) {
String response;
int startPage = 1;
int totalPages = Integer.MAX_VALUE;
List<String> titles = new ArrayList<>();
while (startPage <= totalPages) {
  try {
    URL obj = new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&page=" + startPage);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    while ((response = in.readLine()) != null) {
      JsonObject convertedObject = new Gson().fromJson(response, JsonObject.class);
      totalPages = convertedObject.get("total_pages").getAsInt();
      JsonArray data = convertedObject.getAsJsonArray("data");
      for (int i = 0; i < data.size(); i++) {
        String title = data.get(i).getAsJsonObject().get("Title").getAsString();
        titles.add(title);
      }
    }
    in.close();
    startPage++;
  } catch (Exception ex) {
    ex.printStackTrace();
  }

}
Collections.sort(titles);
return titles.toArray(new String[0]);
}

答案 3 :(得分:2)

您可以使用Java 8 Stream APi

    private String[] getMovieTitlesFromApi(String query) {
  List<String> titlesLst = new ArrayList<>();

IntStream.iterate(1, n -> n + 1).takeWhile(n -> n < totalPages).limit(totalPages).forEach(c -> {

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(
            new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + URLEncoder.encode(query, "UTF-8") + "&page=" + c)
                    .openConnection().getInputStream()))) {

        Supplier<Stream<String>> contentStream =  reader::lines;

        Optional<JsonObject> objectAsJob = contentStream.get()
                .map(contentStreamLine -> new Gson().fromJson(contentStreamLine, JsonObject.class)).findFirst();
        totalPages = objectAsJob.map(convertedLines -> convertedLines.get("total_pages").getAsInt()).get();
        Optional<JsonArray> dataFilter = objectAsJob.map(convertedLines -> convertedLines.getAsJsonArray("data"));

        IntStream.iterate(0, n -> n + 1).takeWhile(n -> n < dataFilter.get().size()).forEach(dataLines -> {
            titlesLst.add(dataFilter.get().get(dataLines).getAsJsonObject().get("Title").getAsString());
            Collections.sort(titlesLst);
        });

    } catch (Exception e) {
        e.printStackTrace();
    }

    totalPages++;
});

storeMovieTitlesInCache(query,  titlesLst.stream().distinct().collect(Collectors.toList()).toArray(new String[0]));
return titlesLst.toArray(new String[0]);
}

答案 4 :(得分:0)

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

import java.net.*;
import com.google.gson.*;

public class Solution{

static String[] getMovieTitles(String substr) {
    String response;
    int startPage = 1;
    int totalPages = Integer.MAX_VALUE;
    List<String> titles = new ArrayList<>();
    while (startPage <= totalPages) {
        try {
            URL obj = new URL(
                    "https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&page=" + startPage);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            while ((response = in.readLine()) != null) {
                JsonObject convertedObject = new Gson().fromJson(response, JsonObject.class);
                totalPages = convertedObject.get("total_pages").getAsInt();
                JsonArray data = convertedObject.getAsJsonArray("data");
                for (int i = 0; i < data.size(); i++) {
                    String title = data.get(i).getAsJsonObject().get("Title").getAsString();
                    titles.add(title);
                }
            }
            in.close();
            startPage++;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }

    }
    Collections.sort(titles);
    return titles.toArray(new String[0]);
}

public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    final String fileName = System.getenv("OUTPUT_PATH");
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    String[] res;
    String _substr;
    try {
        _substr = in.nextLine();
    } catch (Exception e) {
        _substr = null;
    }

    res = getMovieTitles(_substr);
    for (int res_i = 0; res_i < res.length; res_i++) {
        bw.write(String.valueOf(res[res_i]));
        bw.newLine();
    }

    bw.close();
}

}

答案 5 :(得分:0)

这里是a2441918的另一个带有承诺的版本!!

"use strict";
const https = require("https");

const getMovieTitlesData = (title, page = 1) => {
  const url = `https://jsonmock.hackerrank.com/api/movies/search/?Title=${encodeURI(
    title
  )}&page=${page}`;

  const titles = [];
  return new Promise((resolve, reject) => {
    https
      .get(url, function(res) {
        let body = "";
        res.setEncoding("utf-8");
        res.on("data", function(chunk) {
          body += chunk;
        });
        res.on("end", function() {
          let json = JSON.parse(body);
          for (let i = 0; i < json.data.length; i++) {
            titles.push(json.data[i].Title);
          }
          // console.log(json);
          resolve({
            titles: titles,
            page: page,
            total_pages: json.total_pages
          });
        });
      })
      .on("error", function(e) {
        console.error("Got an error: ", e);
        reject(e);
      });
  });
};

function getMovieTitles(substr) {
  const promises = [];
  const titles = [];
  getMovieTitlesData(substr).then(result => {
    titles.push(...result.titles);
    for (let i = result.page + 1; i <= result.total_pages; i++) {
      promises.push(getMovieTitlesData(substr, i));
    }
    Promise.all(promises).then(datas => {
      datas.forEach(data => {
        titles.push(...data.titles);
      });
      console.log(titles.sort());
    });
  });
}

getMovieTitles("spiderman");

答案 6 :(得分:0)

这是我在python中的解决方案:

import requests
import json

def getMovieTitles(substr):
    titles = []  
    data = requests.get("https://jsonmock.hackerrank.com/api/movies/search/?Title={}".format(substr))  
    response = json.loads(data.content.decode('utf-8'))    
    for page in range(0, response["total_pages"]):       
        page_response = requests.get("https://jsonmock.hackerrank.com/api/movies/search/?Title={}&amp;page={}".format(substr, page + 1))    
        page_content = json.loads(page_response.content.decode('utf-8'))
        #print ('page_content', page_content, 'type(page_content)', type(page_content))    
        for item in range(0, len(page_content["data"])):           
             titles.append(str(page_content["data"][item]["Title"]))  
    titles.sort()  
    return titles

print(getMovieTitles("spiderman"))

答案 7 :(得分:0)

使用异步等待

const https = require('https');

// function returns a Promise
const getPromise = (movie_title, page = 1) => {
  return new Promise((resolve, reject) => {
    https.get(
      `https://jsonmock.hackerrank.com/api/movies/search/?Title=${movie_title}&page=${page}`,
      response => {
        let chunks_of_data = [];

        response.on('data', fragments => {
          chunks_of_data.push(fragments);
        });
        response.on('end', () => {
          let data = Buffer.concat(chunks_of_data);
          resolve(JSON.parse(data));
        });
        response.on('error', error => {
          reject(error);
        });
      }
    );
  });
};

// async function to make http request
const makeSynchronousRequest = async movie_title => {
  try {
    // maing a req for number of pages
    let http_promise = getPromise(movie_title);
    let response_body = await http_promise;
    let titles = [];
    for (let page_num = 1; page_num <= response_body.total_pages; page_num++) {
      // maing a req for titles of movies
      let http_promise = getPromise(movie_title, page_num);
      let response_body = await http_promise;
      // holds response from server that is passed when Promise is resolved
      response_body.data.forEach(item => {
        titles.push(item.Title);
      });
    }
    console.log(titles.sort());
  } catch (error) {
    // Promise rejected
    console.log(error);
  }
};

function getMovieTitles(movie_title) {
  makeSynchronousRequest(movie_title);
}

getMovieTitles('batman');

答案 8 :(得分:0)

如果有人在寻找获取作者的文章问题,那么下面是我的Python解决方案

import requests
import json

def getArticleTitles(author):
    # Write your code here
    if not author:  return []
    titles = []
    st, total = 1, float('inf')
    while st <= total:
        url = "https://jsonmock.hackerrank.com/api/articles?author={0}&page={1}".format(author, st)
        response = requests.get(url)
        res = json.loads(response.content)
        total = res['total_pages']

        for t in res['data']:
            if not t['title'] and not t['story_title']:
                continue
            elif not t['title']:
                titles += [t['story_title']]
            else:
                titles += [t['title']]
        st += 1
    return titles

答案 9 :(得分:0)

我感谢HackerRank问题。它使我明白,我不应该过多依赖Spring Boot注释。

这是我无法回答的一个问题,显然我过于依赖使用Spring Boot注释no @JSONProperty, no @RequestBody, and walla I can't do much :)。我是在面试后写的。我希望它很容易理解。

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.net.*;

import com.google.gson.*;

class MovieTitle {
  String Title;
  int Year;
  String imdbID;
}

class JSONResponse {
  int page;
  int per_page;
  int total;
  int total_pages;
  List<MovieTitle> data;
}

public class Solution {
  /*
   * Complete the function below.
   */

  static String[] getMovieTitles(String substr) {
    List<String> titles = new ArrayList<String>();
    int pageNumber = 1;
    int total_pages = 1;

    while (pageNumber <= total_pages) {
      try {
        System.out.println("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&pageNumber=" + pageNumber);
        URL url = new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr + "&pageNumber=" + pageNumber);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");

        String response = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        while ((response = bufferedReader.readLine()) != null) {
          Gson gson = new Gson();
          JSONResponse json = gson.fromJson(response, JSONResponse.class);
          total_pages = json.total_pages;
          List<MovieTitle> data = json.data;
          for (MovieTitle title : data) {
            titles.add(title.Title);
          }
        }
        bufferedReader.close();
        pageNumber++;
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    //complete function here
    return titles.toArray(new String[0]);
  }


  public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    final String fileName = "file.txt";
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    String[] res;
    String _substr;
    try {
      _substr = in.nextLine();
    } catch (Exception e) {
      _substr = null;
    }

    res = getMovieTitles(_substr);
    for (int res_i = 0; res_i < res.length; res_i++) {
      bw.write(String.valueOf(res[res_i]));
      bw.newLine();
    }

    bw.close();
  }
}

答案 10 :(得分:-1)

这是与a2441918相同的代码,但有所改进! 承诺更少的回调

此代码可测试且模块化 也是ES6风格

导入模块

const https = require('https');

URL应该是动态的(可以改进)

const url = (title, pageNum = 1) => 'https://jsonmock.hackerrank.com/api/movies/search/?Title=' + title + "&page=" + pageNum 

分隔get请求,这将允许将其写入一次并根据需要使用多次

function requestGET(url) {
    return new Promise((resolve, reject) => {
        https.get(url, res => {
            console.log(res.statusCode, res.statusCode >= 400)
            if ( res.statusCode >= 200 && res.statusCode < 400 ) {
                res.on('data', body => {
                    resolve(body)
                })
            } 

            if(res.statusCode >= 400) {
                    // since it needs to parse the response
                    // in case of 400 sed back an empty object 
                    // on this method alone can add huge improvement
                    // but that will be a huge waste of time, 
                    // since great libraries are out there 
                    reject(JSON.stringify({}))
                }
            }).on('error', (e) => {
                console.error(`Got error: ${e.message}`);
        })
    })
}

此方法将使代码更具可读性

const convertToString = arr => {
    console.log(arr.join('\n'))
}

最后是结束通话:

function getMovieTitles(substr) {
    fetchData(substr);
}



const res = getMovieTitles('yfvuguoguogguoyguogouyg')