当前位置: 首页>>代码示例>>Java>>正文


Java PostMethod.setRequestBody方法代码示例

本文整理汇总了Java中org.apache.commons.httpclient.methods.PostMethod.setRequestBody方法的典型用法代码示例。如果您正苦于以下问题:Java PostMethod.setRequestBody方法的具体用法?Java PostMethod.setRequestBody怎么用?Java PostMethod.setRequestBody使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.commons.httpclient.methods.PostMethod的用法示例。


在下文中一共展示了PostMethod.setRequestBody方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: assertPostStatus

import org.apache.commons.httpclient.methods.PostMethod; //导入方法依赖的package包/类
protected HttpMethod assertPostStatus(String url, int expectedStatusCode, List<NameValuePair> postParams,
        List<Header> headers, String assertMessage) throws IOException {
    final PostMethod post = new PostMethod(url);
    post.setFollowRedirects(false);

    if (headers != null) {
        for (Header header : headers) {
            post.addRequestHeader(header);
        }
    }

    if (postParams != null) {
        final NameValuePair[] nvp = {};
        post.setRequestBody(postParams.toArray(nvp));
    }

    final int status = H.getHttpClient().executeMethod(post);
    if (assertMessage == null) {
        assertEquals(expectedStatusCode, status);
    } else {
        assertEquals(assertMessage, expectedStatusCode, status);
    }
    return post;
}
 
开发者ID:apache,项目名称:sling-org-apache-sling-launchpad-integration-tests,代码行数:25,代码来源:AuthenticationResponseCodeTest.java

示例2: testPostParametersEncoding

import org.apache.commons.httpclient.methods.PostMethod; //导入方法依赖的package包/类
public void testPostParametersEncoding() throws Exception {
    PostMethod post = new PostMethod();
    post.setRequestBody(new NameValuePair[] { PAIR });
    assertEquals("name=value", getRequestAsString(post.getRequestEntity()));

    post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2 });
    assertEquals("name=value&name1=value1&name2=value2", 
        getRequestAsString(post.getRequestEntity()));

    post.setRequestBody(new NameValuePair[]{ PAIR, PAIR1, PAIR2, new NameValuePair("hasSpace", "a b c d") });
    assertEquals("name=value&name1=value1&name2=value2&hasSpace=a+b+c+d",
        getRequestAsString(post.getRequestEntity()));

    post.setRequestBody(new NameValuePair[]{ new NameValuePair("escaping", ",.-\u00f6\u00e4\[email protected]#*&()=?:;}{[]$") });
    assertEquals("escaping=%2C.-%F6%E4%FC%21%2B%40%23*%26%28%29%3D%3F%3A%3B%7D%7B%5B%5D%24",
        getRequestAsString(post.getRequestEntity()));
    
}
 
开发者ID:jenkinsci,项目名称:lib-commons-httpclient,代码行数:19,代码来源:TestPostParameterEncoding.java

示例3: assertAuthenticatedPostStatus

import org.apache.commons.httpclient.methods.PostMethod; //导入方法依赖的package包/类
/** Execute a POST request and check status */
public void assertAuthenticatedPostStatus(Credentials creds, String url, int expectedStatusCode, List<NameValuePair> postParams, String assertMessage)
throws IOException {
    final PostMethod post = new PostMethod(url);
    post.setFollowRedirects(false);

    URL baseUrl = new URL(HTTP_BASE_URL);
    AuthScope authScope = new AuthScope(baseUrl.getHost(), baseUrl.getPort(), AuthScope.ANY_REALM);
    post.setDoAuthentication(true);
    Credentials oldCredentials = httpClient.getState().getCredentials(authScope);
    try {
        httpClient.getState().setCredentials(authScope, creds);

        if(postParams!=null) {
            final NameValuePair [] nvp = {};
            post.setRequestBody(postParams.toArray(nvp));
        }

        final int status = httpClient.executeMethod(post);
        if(assertMessage == null) {
            assertEquals(expectedStatusCode, status);
        } else {
            assertEquals(assertMessage, expectedStatusCode, status);
        }
    } finally {
        httpClient.getState().setCredentials(authScope, oldCredentials);
    }
}
 
开发者ID:apache,项目名称:sling-org-apache-sling-launchpad-integration-tests,代码行数:29,代码来源:AuthenticatedTestUtil.java

示例4: testUrlEncodedRequestBody

import org.apache.commons.httpclient.methods.PostMethod; //导入方法依赖的package包/类
public void testUrlEncodedRequestBody() throws Exception {

        PostMethod httppost = new PostMethod("/");

        String ru_msg = constructString(RUSSIAN_STUFF_UNICODE); 
        String ch_msg = constructString(SWISS_GERMAN_STUFF_UNICODE); 

        httppost.setRequestBody(new NameValuePair[] {
            new NameValuePair("ru", ru_msg),
            new NameValuePair("ch", ch_msg) 
        });            

        httppost.setRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE 
            + "; charset=" + CHARSET_UTF8);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        httppost.getRequestEntity().writeRequest(bos);
        
        Map params = new HashMap();
        StringTokenizer tokenizer = new StringTokenizer(
            new String(bos.toByteArray(), CHARSET_UTF8), "&");
        while (tokenizer.hasMoreTokens()) {
            String s = tokenizer.nextToken();
            int i = s.indexOf('=');
            assertTrue("Invalid url-encoded parameters", i != -1);
            String name = s.substring(0, i).trim(); 
            String value = s.substring(i + 1, s.length()).trim(); 
            value = URIUtil.decode(value, CHARSET_UTF8);
            params.put(name, value);
        }
        assertEquals(ru_msg, params.get("ru"));
        assertEquals(ch_msg, params.get("ch"));
    }
 
开发者ID:jenkinsci,项目名称:lib-commons-httpclient,代码行数:34,代码来源:TestMethodCharEncoding.java

示例5: getAccessToken

import org.apache.commons.httpclient.methods.PostMethod; //导入方法依赖的package包/类
@SuppressWarnings("deprecation")
public String getAccessToken() {
    if (this.oAuth2AccessToken != null) {
        return this.oAuth2AccessToken;
    }

    try {
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(this.getUsername(), this.getPassword());
        client.getState().setCredentials(AuthScope.ANY, defaultcreds);

        PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
        method.setRequestBody("grant_type=client_credentials");
        int responseCode = client.executeMethod(method);
        if (responseCode != 200) {

            throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
                    + ", got response code " + responseCode);
        }
        String responseBody = method.getResponseBodyAsString();
        JSONObject accessResponse = new JSONObject(responseBody);
        accessResponse.getString("access_token");
        return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
    } catch (Exception e) {
        throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
    }
}
 
开发者ID:wso2-incubator,项目名称:scim2-compliance-test-suite,代码行数:29,代码来源:CSP.java

示例6: getAccessTokenUserPass

import org.apache.commons.httpclient.methods.PostMethod; //导入方法依赖的package包/类
public String getAccessTokenUserPass() {
    if (!StringUtils.isEmpty(this.oAuth2AccessToken)) {
        return this.oAuth2AccessToken;
    }

    if (StringUtils.isEmpty(this.username) || StringUtils.isEmpty(this.password) && StringUtils.isEmpty(this.oAuth2AuthorizationServer)
            || StringUtils.isEmpty(this.oAuth2ClientId) || StringUtils.isEmpty(this.oAuth2ClientSecret)) {
        return "";
    }

    try {
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);

        // post development
        PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
        method.setRequestHeader(new Header("Content-type", "application/x-www-form-urlencoded"));

        method.addRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes()));
        NameValuePair[] body = new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password),
                new NameValuePair("client_id", oAuth2ClientId), new NameValuePair("client_secret", oAuth2ClientSecret),
                new NameValuePair("grant_type", oAuth2GrantType) };
        method.setRequestBody(body);
        int responseCode = client.executeMethod(method);

        String responseBody = method.getResponseBodyAsString();
        if (responseCode != 200) {
            throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
                    + ", got response code " + responseCode);
        }

        JSONObject accessResponse = new JSONObject(responseBody);
        accessResponse.getString("access_token");
        return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
    } catch (Exception e) {
        throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
    }
}
 
开发者ID:wso2-incubator,项目名称:scim2-compliance-test-suite,代码行数:39,代码来源:CSP.java

示例7: deregisterPaymentInformation

import org.apache.commons.httpclient.methods.PostMethod; //导入方法依赖的package包/类
@Override
public void deregisterPaymentInformation(RequestData data)
        throws PaymentDeregistrationException {

    if (data == null) {
        throw new IllegalArgumentException("requestData must not be null!");
    }

    String processingResult = null;
    Exception occurredException = null;
    LogMessageIdentifier failureMessageId = null;
    String[] failureMessageParam = null;

    setProxyForHTTPClient(data);

    PostMethod postMethod = HttpMethodFactory.getPostMethod(data
            .getProperty(HeidelpayConfigurationKey.PSP_XML_URL.name()));
    try {
        Document doc = createDeregistrationRequestDocument(data);

        String result = XMLConverter.convertToString(doc, true);
        NameValuePair nvp = new NameValuePair(LOAD_PARAMETER_NAME, result);
        postMethod.setRequestBody(new NameValuePair[] { nvp });

        client.executeMethod(postMethod);

        String response = postMethod.getResponseBodyAsString();
        HeidelpayResponse heidelPayResponse = new HeidelpayResponse(
                response);
        processingResult = heidelPayResponse.getProcessingResult();

        if (!HeidelpayPostParameter.SUCCESS_RESULT.equals(processingResult)) {
            String returnCode = heidelPayResponse.getProcessingReturnCode();
            failureMessageId = LogMessageIdentifier.ERROR_DEREGISTER_PAYMENT_INFORMATION_IN_PSP_FAILED;
            failureMessageParam = new String[] {
                    String.valueOf(data.getOrganizationId()),
                    String.valueOf(data.getPaymentInfoKey()), returnCode };
        }
    } catch (Exception e) {
        occurredException = e;
        failureMessageId = LogMessageIdentifier.ERROR_DEREGISTER_PAYMENT_INFORMATION__FAILED_ON_PSP_SIDE;
        failureMessageParam = new String[] {
                String.valueOf(data.getPaymentInfoKey()),
                data.getOrganizationId() };
    }

    if (failureMessageId != null) {
        PaymentDeregistrationException pdf = new PaymentDeregistrationException(
                "Deregistration in PSP system failed", occurredException);
        logger.logError(Log4jLogger.SYSTEM_LOG, pdf, failureMessageId,
                failureMessageParam);
        throw pdf;
    }

}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:56,代码来源:PaymentServiceProviderBean.java

示例8: getAuthenticatedPostContent

import org.apache.commons.httpclient.methods.PostMethod; //导入方法依赖的package包/类
/** retrieve the contents of given URL and assert its content type
  * @param expectedContentType use CONTENT_TYPE_DONTCARE if must not be checked
  * @throws IOException
  * @throws HttpException */
 public String getAuthenticatedPostContent(Credentials creds, String url, String expectedContentType, List<NameValuePair> postParams, int expectedStatusCode) throws IOException {
     final PostMethod post = new PostMethod(url);

     URL baseUrl = new URL(HTTP_BASE_URL);
     AuthScope authScope = new AuthScope(baseUrl.getHost(), baseUrl.getPort(), AuthScope.ANY_REALM);
     post.setDoAuthentication(true);
     Credentials oldCredentials = httpClient.getState().getCredentials(authScope);
 	try {
httpClient.getState().setCredentials(authScope, creds);

      if(postParams!=null) {
          final NameValuePair [] nvp = {};
          post.setRequestBody(postParams.toArray(nvp));
      }

      final int status = httpClient.executeMethod(post);
      final InputStream is = post.getResponseBodyAsStream();
      final StringBuffer content = new StringBuffer();
      final String charset = post.getResponseCharSet();
      final byte [] buffer = new byte[16384];
      int n = 0;
      while( (n = is.read(buffer, 0, buffer.length)) > 0) {
          content.append(new String(buffer, 0, n, charset));
      }
      assertEquals("Expected status " + expectedStatusCode + " for " + url + " (content=" + content + ")",
              expectedStatusCode,status);
      final Header h = post.getResponseHeader("Content-Type");
      if(expectedContentType == null) {
          if(h!=null) {
              fail("Expected null Content-Type, got " + h.getValue());
          }
      } else if(CONTENT_TYPE_DONTCARE.equals(expectedContentType)) {
          // no check
      } else if(h==null) {
          fail(
                  "Expected Content-Type that starts with '" + expectedContentType
                  +" but got no Content-Type header at " + url
          );
      } else {
          assertTrue(
              "Expected Content-Type that starts with '" + expectedContentType
              + "' for " + url + ", got '" + h.getValue() + "'",
              h.getValue().startsWith(expectedContentType)
          );
      }
      return content.toString();

 	} finally {
     	httpClient.getState().setCredentials(authScope, oldCredentials);
 	}
 }
 
开发者ID:apache,项目名称:sling-org-apache-sling-launchpad-integration-tests,代码行数:56,代码来源:AuthenticatedTestUtil.java


注:本文中的org.apache.commons.httpclient.methods.PostMethod.setRequestBody方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。