Java - 使用HtmlUnit发送发布请求

时间:2015-06-06 21:13:18

标签: java htmlunit

无法真正找到任何帮助,但我一直在尝试使用HtmlUnit发送帖子请求。我的代码是:

final WebClient webClient = new WebClient();

// Instead of requesting the page directly we create a WebRequestSettings object
WebRequest requestSettings = new WebRequest(
  new URL("www.URLHERE.com"), HttpMethod.POST);

// Then we set the request parameters
requestSettings.setRequestParameters(new ArrayList());
requestSettings.getRequestParameters().add(new NameValuePair("name", "value"));
// Finally, we can get the page
HtmlPage page = webClient.getPage(requestSettings);

我可以更轻松地执行POST请求吗?

2 个答案:

答案 0 :(得分:13)

这就是它的完成方式

public void post() throws Exception
{

    URL url = new URL("YOURURL");
    WebRequest requestSettings = new WebRequest(url, HttpMethod.POST);

    requestSettings.setAdditionalHeader("Accept", "*/*");
    requestSettings.setAdditionalHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    requestSettings.setAdditionalHeader("Referer", "REFURLHERE");
    requestSettings.setAdditionalHeader("Accept-Language", "en-US,en;q=0.8");
    requestSettings.setAdditionalHeader("Accept-Encoding", "gzip,deflate,sdch");
    requestSettings.setAdditionalHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
    requestSettings.setAdditionalHeader("X-Requested-With", "XMLHttpRequest");
    requestSettings.setAdditionalHeader("Cache-Control", "no-cache");
    requestSettings.setAdditionalHeader("Pragma", "no-cache");
    requestSettings.setAdditionalHeader("Origin", "https://YOURHOST");

    requestSettings.setRequestBody("REQUESTBODY");

    Page redirectPage = webClient.getPage(requestSettings);
}

您可以根据需要自定义它。添加/删除标题,添加/删除请求正文......等等。

答案 1 :(得分:-1)

您可以使用n个可能的库来调用其余的Web服务。

1)Apache Http客户端 2)从广场改造 3)来自谷歌的排球

我使用过Http Apache客户端和Retrofit。两者都很棒。

以下是发送Post请求的Apache HTTP客户端的代码示例

String token = null;

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost postRequest = new HttpPost(LOGIN_URL);
    StringBuilder sb = new StringBuilder();
    sb.append("{\"userName\":\"").append(user).append("\",").append("\"password\":\"").append(password).append("\"}");
    String content = sb.toString();
    StringEntity input = new StringEntity(content);
    input.setContentType("application/json");
    postRequest.setHeader("Content-Type", "application/json");
    postRequest.setHeader("Accept", "application/json");

    postRequest.setEntity(input);

    HttpResponse response = httpClient.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 201)
    {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }

    Header[] headers = response.getHeaders("X-Auth-Token");

    if (headers != null && headers.length > 0)
    {
        token = headers[0].getValue();
    }

    return token;