Httpclient-4.5.2.jar setEntity显示"找不到符号" (JAVA - netbeans 8)

时间:2016-07-12 13:48:04

标签: java apache-httpclient-4.x

我正在尝试使用我从网站上获得的一些代码,这些代码通过API(http://developer.fantasydata.com)公开提供体育数据。

该网站提供了一些示例JAVA代码来发出http请求。由于某种原因,声明的请求(请求)的setEntity方法显示"找不到符号错误。

    package epl.fixtures.test.app;

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.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class EPLFixturesTestApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        HttpClient httpclient = HttpClients.createDefault();

        try
        {
            URIBuilder builder = new URIBuilder("https://api.fantasydata.net/soccer/v2/json/CompetitionDetails/EPL");


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


            // Request body
            StringEntity reqEntity = new StringEntity("{body}");
            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());
        }

    }

}

导致问题的一行是 request.setEntity(reqEntity);

有人能解释一下吗?我将来自apache的所有相关jar文件添加到项目库目录中。

由于

1 个答案:

答案 0 :(得分:0)

HttpGet没有setEntity方法。 这是有道理的,因为请求正文在GET请求中没有任何意义。

只有实现HttpEntityEnclosingRequest的类才有此方法。

我不知道文档为什么会使用它,但是当省略这两行时看起来很有效(无论如何看起来毫无意义)。代码:

URIBuilder builder = new URIBuilder("https://api.fantasydata.net/soccer/v2/json/CompetitionDetails/EPL");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "****************");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();

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