2017-04-02 355 views
-1

我正在使用來自Microsoft Cognitive Services的示例代碼。它使用StringEntity類向REST API發出請求。 java編譯器似乎無法找到'symbol'StringEntity?這可能是什麼原因以及如何解決這個問題? 這裏去的代碼 -即使導入org.apache.http包後,爲什麼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()); 
     } 
    } 
} 

大部分是從微軟API測試樣品取出。 https://dev.cognitive.microsoft.com/docs/services/56b43f72cf5ff8098cef380a/operations/56b449fbcf5ff81038d15cdf

+0

你導入的jar?你在使用maven嗎?還是你手動導入罐子? –

+0

如果你正在使用maven或gradle,請更新project.seems,如jar在構建路徑中不正確。 –

+0

@Rajith Pemabandu,休息非所需的類顯示任何錯誤,只有StringEntity顯示,所以我想問題不是與進口。我想知道在什麼包字符串實體放置?我導入了整個導入org.apache.http。*;程序包,但它仍然無法工作。 –

回答

1

StringEntity是在包org.apache.http.entity,所以你必須添加正確的進口爲:

import org.apache.http.entity.StringEntity 
+0

做'import org.apache.http。*';不包含此導入? –

+0

否。子包不會自動導入。 – dunni