如何向所有HttpClient请求方法添加参数?

时间:2012-12-26 17:18:33

标签: java http rest apache-httpclient-4.x

我正在编写一些使用Apache HttpClient版本4.2.2来访问RESTful第三方API的Java代码。此API包含使用HTTP GETPOSTPUTDELETE的方法。重要的是要注意我使用的是4.xx版本,而不是3.xx,因为API从3变为4。我发现的所有相关示例都是针对3.xx版本。

所有API调用都要求您提供api_key作为参数(关于您使用的方法)。这意味着关于我是否正在进行GET,POST或其他方式,我需要提供此api_key以便对服务器端进行身份验证调用。

// Have to figure out a way to get this into my HttpClient call,
// regardless of whether I'm using: HttpGet, HttpPost, HttpPut
// or HttpDelete...
String api_key = "blah-whatever-my-unique-api-key";

所以我试图弄清楚如何HttpClient提供api_key,而不管我的请求方法(这又取决于我试图点击的RESTful API方法)。看起来HttpGet甚至不支持参数的概念,HttpPost使用名为HttpParams的内容;但是这些HttpParams似乎只存在于HttpClient的3.x.x版本中。

所以我问:api_key字符串附加/添加到所有四个的正确的v4.2.2方法是什么:

  • HttpGet
  • HttpPost
  • HttpPut
  • HttpDelete

提前致谢。

3 个答案:

答案 0 :(得分:22)

您可以使用 URIBuilder 类为所有HTTP方法构建请求URI。 URI构建器提供 setParameter 方法来设置参数。

URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.google.com").setPath("/search")
    .setParameter("q", "httpclient")
    .setParameter("btnG", "Google Search")
    .setParameter("aq", "f")
    .setParameter("oq", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());

输出应为

http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq= 

答案 1 :(得分:2)

如果您想传递一些http参数并发送json请求,也可以使用此方法:

(注意:我添加了一些额外的代码,只是为了帮助其他任何未来的读者和导入来自org.apache.http客户端库)

public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {

    //add the http parameters you wish to pass
    List<NameValuePair> postParameters = new ArrayList<>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    //Build the server URI together with the parameters you wish to pass
    URIBuilder uriBuilder = new URIBuilder("http://google.ug");
    uriBuilder.addParameters(postParameters);

    HttpPost postRequest = new HttpPost(uriBuilder.build());
    postRequest.setHeader("Content-Type", "application/json");

    //this is your JSON string you are sending as a request
    String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";

    //pass the json string request in the entity
    HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
    postRequest.setEntity(entity);

    //create a socketfactory in order to use an http connection manager
    PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);

    connManager.setMaxTotal(20);
    connManager.setDefaultMaxPerRoute(20);

    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(HttpClientPool.connTimeout)
            .setConnectTimeout(HttpClientPool.connTimeout)
            .setConnectionRequestTimeout(HttpClientPool.readTimeout)
            .build();

    // Build the http client.
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();

    CloseableHttpResponse response = httpclient.execute(postRequest);

    //Read the response
    String responseString = "";

    int statusCode = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();

    HttpEntity responseHttpEntity = response.getEntity();

    InputStream content = responseHttpEntity.getContent();

    BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
    String line;

    while ((line = buffer.readLine()) != null) {
        responseString += line;
    }

    //release all resources held by the responseHttpEntity
    EntityUtils.consume(responseHttpEntity);

    //close the stream
    response.close();

    // Close the connection manager.
    connManager.close();
}

答案 2 :(得分:0)

这里重要的是要明确说明必须使用的apache包,因为有不同的方法来实现get请求。

例如,您可以使用Apache CommonsHttpComponents。 在此示例中,我将使用HttpComponents (org.apache.http.*)

请求类:

package request;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import Task;

public void sendRequest(Task task) throws URISyntaxException {

    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme("http")
            .setHost("localhost")
            .setPort(8080)
            .setPath("/TesteHttpRequest/TesteDoLucas")
            .addParameter("className", task.getClassName())
            .addParameter("dateExecutionBegin", task.getDateExecutionBegin())
            .addParameter("dateExecutionEnd", task.getDateExecutionEnd())
            .addParameter("lastDateExecution", task.getDateLastExecution())
            .addParameter("numberExecutions", Integer.toString(task.getNumberExecutions()))
            .addParameter("idTask", Integer.toString(task.getIdTask()))
            .addParameter("numberExecutions" , Integer.toString(task.getNumberExecutions()));
    URI uri = uriBuilder.build();

    HttpGet getMethod = new HttpGet(uri);

    CloseableHttpClient httpclient = HttpClients.createDefault();

    CloseableHttpResponse response = null;

    try {
        response = httpclient.execute(getMethod);
    } catch (IOException e) {
        //handle this IOException properly in the future
    } catch (Exception e) {
        //handle this IOException properly in the future
    }
}

我正在使用Tomcat v7.0 Server,然后上面的类接收任务并将其发送到链接 http://localhost:8080/TesteHttpRequest/TesteDoLucas 中的特定servlet。

我的动态Web项目名为 TesteHttpRequest ,我的servlet通过url / TesteDoLucas

进行注册

任务类:

package bean;

public class Task {

    private int idTask;
    private String taskDescription;
    private String dateExecutionBegin;
    private String dateExecutionEnd;
    private String dateLastExecution;
    private int numberExecutions;
    private String className;

    public int getIdTask() {
        return idTask;
    }

    public void setIdTask(int idTask) {
        this.idTask = idTask;
    }

    public String getTaskDescription() {
        return taskDescription;
    }

    public void setTaskDescription(String taskDescription) {
        this.taskDescription = taskDescription;
    }

    public String getDateExecutionBegin() {
        return dateExecutionBegin;
    }

    public void setDateExecutionBegin(String dateExecutionBegin) {
        this.dateExecutionBegin = dateExecutionBegin;
    }

    public String getDateExecutionEnd() {
        return dateExecutionEnd;
    }

    public void setDateExecutionEnd(String dateExecutionEnd) {
        this.dateExecutionEnd = dateExecutionEnd;
    }

    public String getDateLastExecution() {
        return dateLastExecution;
    }

    public void setDateLastExecution(String dateLastExecution) {
        this.dateLastExecution = dateLastExecution;
    }

    public int getNumberExecutions() {
        return numberExecutions;
    }

    public void setNumberExecutions(int numberExecutions) {
        this.numberExecutions = numberExecutions;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
}

Servlet类:

package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/TesteDoLucas")
public class TesteHttpRequestServlet extends HttpServlet {
     private static final long serialVersionUID = 1L;

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String query = request.getQueryString();
        System.out.println(query);
     }

     protected void doPost(HttpServletRequest request, HttpServletResponse   response) throws ServletException, IOException {
        doGet(request, response);
        }
    }

发送的查询参数将显示在控制台上。

  

的className = java.util.Objects%3B&安培; dateExecutionBegin = 2016%2F04%2F07 + 22%3A22%3A22&安培; dateExecutionEnd = 2016%2F04%2F07 + 06%3A06%3A06&安培; lastDateExecution = 2016%2F04%2F07 + 11 %3A11 3A11%&安培; numberExecutions = 10安培; idTask = 1&安培; numberExecutions = 10

要修复编码,您可以在此处查看:HttpServletRequest UTF-8 Encoding