为什么即使在导入org.apache.http包之后java也找不到StringEntity类?

时间:2017-04-02 06:29:06

标签: java apache api

我正在使用Microsoft Cognitive Services的示例代码。它利用StringEntity类向REST API发出请求。 java编译器似乎无法找到符号' StringEntity?可能是什么原因以及如何解决这个问题? 这是代码 -

import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.*;


public class NEWS_FETCHER 
{
    public static void main(String[] args) 
    {
        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.cognitive.microsoft.com/bing/v5.0/news/search");

            builder.setParameter("q", "microsoft");
            builder.setParameter("count", "10");
            builder.setParameter("offset", "0");
            builder.setParameter("mkt", "en-us");
            builder.setParameter("safeSearch", "Moderate");

            URI uri = builder.build();
            HttpGet request = new HttpGet(uri);
            request.setHeader("Ocp-Apim-Subscription-Key", "<Key goes here>");

            // Request body
            StringEntity reqEntity = new StringEntity("");
            request.setEntity(reqEntity);

            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) 
            {
                System.out.println(EntityUtils.toString(entity));
            }
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

大部分内容来自Microsoft API Test Sample。 https://dev.cognitive.microsoft.com/docs/services/56b43f72cf5ff8098cef380a/operations/56b449fbcf5ff81038d15cdf

1 个答案:

答案 0 :(得分:2)

StringEntity位于包org.apache.http.entity中,因此您必须为其添加正确的导入:

import org.apache.http.entity.StringEntity