构建发布请求

时间:2017-04-11 05:15:20

标签: java apache http post

当我在此行上设置实体时,我正在尝试使用Apache HTTP components在java 中发出帖子后请求

httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

它说

  

“构造函数UrlEncodedFormEntity(List,String)未定义”,我不确定原因。

这是我的整个代码

@Component
public class ScheduledTasks {

@Scheduled(cron="0 9 1-7 * 1 *")    //first monday of each month, at 9am
public void dataLoaderTask() throws Exception   {
    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("https://erudite-master-api-awsmaui.lab.expts.net/erudite/search");
        List<NameValuePair> params = new ArrayList<NameValuePair>(3);
            params.add(new NameValuePair("action", "count"));
            params.add(new NameValuePair("fields", "Status"));
            params.add(new NameValuePair("filters", ""));
        httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

            //Execute and get the response.
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    // do something useful
                } finally {
                    instream.close();
                }
            }
    }

我搜索的每个资源都显示这是正确的方法,所以我不确定为什么它返回undefined。

1 个答案:

答案 0 :(得分:0)

可能存在冲突的Apache HTTP Components JAR文件。 我尝试了下面的代码,没有编译错误: 这些是类路径中使用的两个JAR文件:http-client-4.5.3.jar,http-core-4.4.6.jar。使用spring-boot将确保存储库中最新版本的开源JAR文件。

@Scheduled(cron = "0 9 1-7 * 1 *") // first monday of each month, at 9am
public void dataLoaderTask() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost("https://erudite-master-api-awsmaui.lab.expts.net/erudite/search");
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("action", "count"));
    params.add(new BasicNameValuePair("fields", "Status"));
    params.add(new BasicNameValuePair("filters", ""));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    // Execute and get the response.
    CloseableHttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        try {
            // do something useful
        } finally {
            instream.close();
        }
    }
}