有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在安卓中对URL列表发出多个get请求

我基本上有一个字符串列表(大约20到60个字符串),我想用列表中的每个项目发送一个post请求(并获得json格式的结果,并从响应中向新列表附加一个特定值)。我想对特定数量的工作线程使用ThreadPoolExecutor

我尝试了几件事,但不幸的是我做不到。我可以一次做一个请求,但效率不高,而且需要很长时间

我用python编写了这段代码,它完全实现了我想要做的事情,但不幸的是,我无法用Java重现它

#This function makes a single request using one string from the list
def getname(id):
        url = "https://api-public-service.battledash.co/fortnite/cosmetics/search/id?q=" + id
    with requests.session() as ss:
        l = ss.get(url).json()
#we return a value from the response

    return(l['readableName'])




def getnamelist(ids):
    result = []
    ids = deque(ids)
#Turning the list into a dict and back to list in order to remove duplicated items
    ids = list(dict.fromkeys(ids))
#max workers is set to 10
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
#running the getname function which sends a single request and return a name from id
        results = executor.map(getname,ids)
#appending all results into a list
    for it in tuple(results):
        result.append(it)

    return(result)

共 (1) 个答案

  1. # 1 楼答案

    注意:由于您没有指定Java版本,因此我的答案针对Java>;=八,

    假设您有以下线程安全的函数:public SomeHttpResponseType performGetRequest(String url)

    public List<SomeHttpResponseType> performGetRequests(List<String> urls) {
       return urls.stream().parallelStream()
           .map(this::performGetRequest)
           .collect(Collectors.toList())
    }
    

    这使用默认的ForkJoinPool。如果要指定自己的线程池,请尝试以下操作:

    ForkJoinPool forkJoinPool = null;
    
        try {
            forkJoinPool = new ForkJoinPool(parallelism);
            forkJoinPool.submit(() ->
               urls.stream().parallelStream()
               .map(this::performGetRequest)
               .collect(Collectors.toList())
            ).get()
        } catch(InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            if (forkJoinPool != null) {
                forkJoinPool.shutdown(); //always remember to shutdown the pool
            }
        }
    

    (改编版https://www.codementor.io/nitinpuri/controlling-parallelism-of-java-8-collection-streams-umex0qbt1