當前位置: 首頁>>代碼示例>>Java>>正文


Java PostMethod.setRequestHeader方法代碼示例

本文整理匯總了Java中org.apache.commons.httpclient.methods.PostMethod.setRequestHeader方法的典型用法代碼示例。如果您正苦於以下問題:Java PostMethod.setRequestHeader方法的具體用法?Java PostMethod.setRequestHeader怎麽用?Java PostMethod.setRequestHeader使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.commons.httpclient.methods.PostMethod的用法示例。


在下文中一共展示了PostMethod.setRequestHeader方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: post

import org.apache.commons.httpclient.methods.PostMethod; //導入方法依賴的package包/類
@Override
public HttpResponse post(URL urlObj, byte[] payload, String userName, String password,
                         int timeout) {
  HttpClient client = new HttpClient();
  PostMethod method = new PostMethod(urlObj.toString());
  method.setRequestEntity(new ByteArrayRequestEntity(payload));
  method.setRequestHeader("Content-type", "application/json");
  client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
      new DefaultHttpMethodRetryHandler());
  client.getParams().setSoTimeout(1000 * timeout);
  client.getParams().setConnectionManagerTimeout(1000 * timeout);
  if (userName != null && password != null) {
    setBasicAuthorization(method, userName, password);
  }
  try {
    int response = client.executeMethod(method);
    return new HttpResponse(response, method.getResponseBody());
  } catch (IOException e) {
    throw new RuntimeException("Failed to process post request URL: " + urlObj, e);
  } finally {
    method.releaseConnection();
  }

}
 
開發者ID:logistimo,項目名稱:logistimo-web-service,代碼行數:25,代碼來源:LogiURLFetchService.java

示例2: createPostMethod

import org.apache.commons.httpclient.methods.PostMethod; //導入方法依賴的package包/類
private PostMethod createPostMethod(KalturaParams kparams,
		KalturaFiles kfiles, String url) {
	PostMethod method = new PostMethod(url);
       method.setRequestHeader("Accept","text/xml,application/xml,*/*");
       method.setRequestHeader("Accept-Charset","utf-8,ISO-8859-1;q=0.7,*;q=0.5");
       
       if (!kfiles.isEmpty()) {        	
           method = this.getPostMultiPartWithFiles(method, kparams, kfiles);        	
       } else {
           method = this.addParams(method, kparams);            
       }
       
       if (isAcceptGzipEncoding()) {
		method.addRequestHeader(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
	}
       

	// Provide custom retry handler is necessary
	method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
			new DefaultHttpMethodRetryHandler (3, false));
	return method;
}
 
開發者ID:ITYug,項目名稱:kaltura-ce-sakai-extension,代碼行數:23,代碼來源:KalturaClientBase.java

示例3: getPostResponseHeader

import org.apache.commons.httpclient.methods.PostMethod; //導入方法依賴的package包/類
public static String getPostResponseHeader(String url,String argJson,List<UHeader> headerList,String headerName){
  	String info = "";
  	try {
   	HttpClient client = new HttpClient();
	PostMethod method = new PostMethod(url);
	client.getParams().setContentCharset("UTF-8");
	if(headerList.size()>0){
		for(int i = 0;i<headerList.size();i++){
			UHeader header = headerList.get(i);
			method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue());
		}
	}
	method.getParams().setParameter(
			HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
	if(argJson != null && !argJson.trim().equals("")) {
		RequestEntity requestEntity = new StringRequestEntity(argJson,"application/json","UTF-8");
		method.setRequestEntity(requestEntity);
	}
	method.releaseConnection();
	Header h =  method.getResponseHeader(headerName);
	info = h.getValue();
} catch (IOException e) {
	e.printStackTrace();
}
  	return info;
  }
 
開發者ID:noseparte,項目名稱:Spring-Boot-Server,代碼行數:27,代碼來源:HttpUtils.java

示例4: getHttpPost

import org.apache.commons.httpclient.methods.PostMethod; //導入方法依賴的package包/類
private static PostMethod getHttpPost(String url, String cookie,
									  String userAgent) {
	PostMethod httpPost = new PostMethod(url);
	httpPost.getParams().setSoTimeout(TIMEOUT_SOCKET);
	httpPost.setRequestHeader("Connection", "Keep-Alive");
	httpPost.setRequestHeader("User-Agent", userAgent);
	return httpPost;
}
 
開發者ID:PlutoArchitecture,項目名稱:Pluto-Android,代碼行數:9,代碼來源:ApiClient.java

示例5: createPostMethod

import org.apache.commons.httpclient.methods.PostMethod; //導入方法依賴的package包/類
/**
 * Creates the post method used to send the SOAP request.
 * 
 * @param endpoint endpoint to which the message is sent
 * @param requestParams HTTP request parameters
 * @param message message to be sent
 * 
 * @return the post method to be used to send this message
 * 
 * @throws SOAPClientException thrown if the message could not be marshalled
 */
protected PostMethod createPostMethod(String endpoint, HttpSOAPRequestParameters requestParams, Envelope message)
        throws SOAPClientException {
    log.debug("POSTing SOAP message to {}", endpoint);

    PostMethod post = new PostMethod(endpoint);
    post.setRequestEntity(createRequestEntity(message, Charset.forName("UTF-8")));
    if (requestParams != null && requestParams.getSoapAction() != null) {
        post.setRequestHeader(HttpSOAPRequestParameters.SOAP_ACTION_HEADER, requestParams.getSoapAction());
    }

    return post;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:24,代碼來源:HttpSOAPClient.java

示例6: 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

示例7: testRequestConnClose

import org.apache.commons.httpclient.methods.PostMethod; //導入方法依賴的package包/類
public void testRequestConnClose() throws Exception {
    this.server.setRequestHandler(new HttpRequestHandler() {
       
        public boolean processRequest(
                final SimpleHttpServerConnection conn,
                final SimpleRequest request) throws IOException {

            // Make sure the request if fully consumed
            request.getBodyBytes();
            
            SimpleResponse response = new SimpleResponse();
            response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK);
            response.setBodyString("stuff back");

            conn.setKeepAlive(true);
            conn.writeResponse(response);
            
            return true;
        }
        
    });

    AccessibleHttpConnectionManager connman = new AccessibleHttpConnectionManager();
    
    this.client.getParams().setVersion(HttpVersion.HTTP_1_0);
    this.client.setHttpConnectionManager(connman);
    
    PostMethod httppost = new PostMethod("/test/");
    httppost.setRequestHeader("Connection", "close");
    httppost.setRequestEntity(new StringRequestEntity("stuff", null, null));
    try {
        this.client.executeMethod(httppost);
    } finally {
        httppost.releaseConnection();
    }
    assertFalse(connman.getConection().isOpen());
}
 
開發者ID:jenkinsci,項目名稱:lib-commons-httpclient,代碼行數:38,代碼來源:TestConnectionPersistence.java

示例8: 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

示例9: main

import org.apache.commons.httpclient.methods.PostMethod; //導入方法依賴的package包/類
/**
 *
 * Usage:
 *          java PostSOAP http://mywebserver:80/ SOAPAction c:\foo.xml
 *
 *  @param args command line arguments
 *                 Argument 0 is a URL to a web server
 *                 Argument 1 is the SOAP Action
 *                 Argument 2 is a local filename
 *
 */
public static void main(String[] args) throws Exception {
    if (args.length != 3) {
        System.out.println("Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] PostSOAP <url> <soapaction> <filename>]");
        System.out.println("<classpath> - must contain the commons-httpclient.jar and commons-logging.jar");
        System.out.println("<loglevel> - one of error, warn, info, debug, trace");
        System.out.println("<url> - the URL to post the file to");
        System.out.println("<soapaction> - the SOAP action header value");
        System.out.println("<filename> - file to post to the URL");
        System.out.println();
        System.exit(1);
    }
    // Get target URL
    String strURL = args[0];
    // Get SOAP action
    String strSoapAction = args[1];
    // Get file to be posted
    String strXMLFilename = args[2];
    File input = new File(strXMLFilename);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    // consult documentation for your web service
    post.setRequestHeader("SOAPAction", strSoapAction);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        System.out.println("Response body: ");
        System.out.println(post.getResponseBodyAsString());
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}
 
開發者ID:jenkinsci,項目名稱:lib-commons-httpclient,代碼行數:53,代碼來源:PostSOAP.java


注:本文中的org.apache.commons.httpclient.methods.PostMethod.setRequestHeader方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。