本文整理汇总了Java中org.apache.commons.httpclient.HttpMethod类的典型用法代码示例。如果您正苦于以下问题:Java HttpMethod类的具体用法?Java HttpMethod怎么用?Java HttpMethod使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpMethod类属于org.apache.commons.httpclient包,在下文中一共展示了HttpMethod类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: get
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
@Override
public HttpResponse get(URL urlObj, String userName, String password, int timeout) {
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(urlObj.toString());
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 get " + urlObj.toString(), e);
} finally {
method.releaseConnection();
}
}
示例2: testSuccessfulVerifyTargetOverHttps
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
public void testSuccessfulVerifyTargetOverHttps() throws Exception
{
//Stub HttpClient so that executeMethod returns a 200 response
when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class),
any(HttpState.class))).thenReturn(200);
target.setEndpointProtocol(HTTPS_PROTOCOL);
target.setEndpointPort(HTTPS_PORT);
//Call verifyTarget
transmitter.verifyTarget(target);
ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
assertEquals("port", HTTPS_PORT, hostConfig.getValue().getPort());
assertTrue("socket factory",
hostConfig.getValue().getProtocol().getSocketFactory() instanceof SecureProtocolSocketFactory);
assertEquals("protocol", HTTPS_PROTOCOL.toLowerCase(),
hostConfig.getValue().getProtocol().getScheme().toLowerCase());
}
示例3: getData
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
public List<DataPoint> getData ( final String item, final String type, final Date from, final Date to, final Integer number ) throws Exception
{
final HttpClient client = new HttpClient ();
final HttpMethod method = new GetMethod ( this.baseUrl + "/" + URLEncoder.encode ( item, "UTF-8" ) + "/" + URLEncoder.encode ( type, "UTF-8" ) + "?from=" + URLEncoder.encode ( Utils.isoDateFormat.format ( from ), "UTF-8" ) + "&to=" + URLEncoder.encode ( Utils.isoDateFormat.format ( to ), "UTF-8" ) + "&no=" + number );
client.getParams ().setSoTimeout ( (int)this.timeout );
try
{
final int status = client.executeMethod ( method );
if ( status != HttpStatus.SC_OK )
{
throw new RuntimeException ( "Method failed with error " + status + " " + method.getStatusLine () );
}
return Utils.fromJson ( method.getResponseBodyAsString () );
}
finally
{
method.releaseConnection ();
}
}
示例4: createDeleteMethod
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private HttpMethod createDeleteMethod(HttpServletRequest req, String redirectUrl) throws IOException, ServletException, NotLoggedInException {
DeleteMethod delete = new DeleteMethod(redirectUrl);
addUserNameToHeader(delete, req);
addAcceptEncodingHeader(delete, req);
delete.getParams().setContentCharset("UTF-8");
HttpMethodParams params = new HttpMethodParams();
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
String paramName = (String) e.nextElement();
String[] values = req.getParameterValues(paramName);
for (String value : values) {
params.setParameter(paramName, value);
}
}
delete.setParams(params);
return delete;
}
示例5: doService
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
private void doService(HttpMethod method, HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
outputRequestLog(req);
InputStream iStream = null;
ServletOutputStream oStream = null;
try {
long threadID = Thread.currentThread().getId();
log.debug("[" + threadID + "] forwarded to " + distributer.getRedirectUrl(req));
HttpClient client = new HttpClient();
log.debug("[" + threadID + "]send request.");
int resultCode = client.executeMethod(method);
log.debug("[" + threadID + "]got response: result code is " + resultCode);
res.setStatus(resultCode);
for (Header header : method.getResponseHeaders()) {
res.setHeader(header.getName(), header.getValue());
}
iStream = method.getResponseBodyAsStream();
oStream = res.getOutputStream();
writeOutputStream(iStream, oStream);
log.debug("[" + threadID + "] response sent to client.");
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ServletException(e.getMessage(), e);
} finally {
if (iStream != null) {
iStream.close();
}
if (oStream != null) {
oStream.close();
}
}
}
示例6: authenticateResponse
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public boolean authenticateResponse(HttpMethod method, String remoteIP, byte[] decryptedBody)
{
try
{
byte[] expectedMAC = getResponseMac(method);
Long timestamp = getResponseTimestamp(method);
if(timestamp == null)
{
return false;
}
remoteIP = IPUtils.getRealIPAddress(remoteIP);
return authenticate(expectedMAC, new MACInput(decryptedBody, timestamp.longValue(), remoteIP));
}
catch(Exception e)
{
throw new RuntimeException("Unable to authenticate HTTP response", e);
}
}
示例7: setRequestAuthentication
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
/**
* {@inheritDoc}
*/
@Override
public void setRequestAuthentication(HttpMethod method, byte[] message) throws IOException
{
long requestTimestamp = System.currentTimeMillis();
// add MAC header
byte[] mac = macUtils.generateMAC(KeyProvider.ALIAS_SOLR, new MACInput(message, requestTimestamp, getLocalIPAddress()));
if(logger.isDebugEnabled())
{
logger.debug("Setting MAC " + Arrays.toString(mac) + " on HTTP request " + method.getPath());
logger.debug("Setting timestamp " + requestTimestamp + " on HTTP request " + method.getPath());
}
setRequestMac(method, mac);
// prevent replays
setRequestTimestamp(method, requestTimestamp);
}
示例8: setHeaders
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
/**
* Will write all request headers stored in the request to the method that
* are not in the set of banned headers.
* The Accept-Endocing header is also changed to allow compressed content
* connection to the server even if the end client doesn't support that.
* A Via headers is created as well in compliance with the RFC.
*
* @param method The HttpMethod used for this connection
* @param request The incoming request
* @throws HttpException
*/
protected void setHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
Enumeration headers = request.getHeaderNames();
String connectionToken = request.getHeader("connection");
while (headers.hasMoreElements()) {
String name = (String) headers.nextElement();
boolean isToken = (connectionToken != null && name.equalsIgnoreCase(connectionToken));
if (!isToken && !bannedHeaders.contains(name.toLowerCase())) {
Enumeration value = request.getHeaders(name);
while (value.hasMoreElements()) {
method.addRequestHeader(name, (String) value.nextElement());
}
}
}
setProxySpecificHeaders(method, request);
}
示例9: charge_communicationFailureDetailedInfo_Bug8712
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
@Test
public void charge_communicationFailureDetailedInfo_Bug8712()
throws Exception {
// setup
ChargingData chargingData = createChargingData();
RequestData requestData = createRequestData(DIRECT_DEBIT);
PostMethodStub.setStubReturnValue(sampleResponse);
when(
Integer.valueOf(httpClientMock
.executeMethod(any(HttpMethod.class)))).thenThrow(
new IOException());
// Check error message provides details in case of communication failure
try {
psp.charge(requestData, chargingData);
Assert.fail(PSPCommunicationException.class.getName() + " expected");
} catch (PSPCommunicationException pspEx) {
final String ERROR_MSG = pspEx.getMessage();
Assert.assertTrue(ERROR_MSG.indexOf("[Details]") > 0);
Assert.assertTrue(ERROR_MSG.indexOf(XML_URL) > 0);
Assert.assertTrue(ERROR_MSG
.indexOf(HeidelpayXMLTags.XML_ATTRIBUTE_CHANNEL) > 0);
Assert.assertTrue(ERROR_MSG
.indexOf(HeidelpayXMLTags.XML_ATTRIBUTE_LOGIN) > 0);
}
}
示例10: testPreventLoopIncorrectHttpBasicCredentials
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
@Test
public void testPreventLoopIncorrectHttpBasicCredentials() throws Exception {
// assume http and webdav are on the same host + port
URL url = new URL(HttpTest.HTTP_BASE_URL);
Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage");
H.getHttpClient().getState()
.setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);
final String requestUrl = HttpTest.HTTP_BASE_URL + "/junk?param1=1";
HttpMethod get = new GetMethod(requestUrl);
get.setRequestHeader("Referer", requestUrl);
get.setRequestHeader("User-Agent", "Mozilla/5.0 Sling Integration Test");
int status = H.getHttpClient().executeMethod(get);
assertEquals(HttpServletResponse.SC_UNAUTHORIZED, status);
}
开发者ID:apache,项目名称:sling-org-apache-sling-launchpad-integration-tests,代码行数:17,代码来源:AuthenticationResponseCodeTest.java
示例11: httpClient3Test
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
/**
* 同步客户端3.X版本
*
* @return
*/
@GET
@Path("httpclient3test")
public String httpClient3Test() {
HttpClient httpClient = new HttpClient();
HttpMethod method = new GetMethod("https://www.baidu.com/");
try {
httpClient.executeMethod(method);
System.out.println(method.getURI());
System.out.println(method.getStatusLine());
System.out.println(method.getName());
System.out.println(method.getResponseHeader("Server").getValue());
System.out.println(method.getResponseBodyAsString());
}
catch (Exception e) {
e.printStackTrace();
}
return "httpClient3 test success";
}
示例12: tryDownloadAndSaveFile
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
/**
* Method uses given method parameter to connect to the server and tries to download.<br />
* Method updates download state of HttpFile automatically - sets <code>DownloadState.GETTING</code> and then <code>DownloadState.DOWNLOADING</code>
*
* @param method HttpMethod - its URL should be a link to the file
* @return true if file was successfully downloaded, false otherwise - file was not found, only string content is available
* @throws Exception when connection/writing to file failed
*/
protected boolean tryDownloadAndSaveFile(HttpMethod method) throws Exception {
if (httpFile.getState() == DownloadState.PAUSED || httpFile.getState() == DownloadState.CANCELLED)
return false;
else
httpFile.setState(DownloadState.GETTING);
if (logger.isLoggable(Level.INFO)) {
logger.info("Download link URI: " + method.getURI().toString());
logger.info("Making final request for file");
}
try {
final InputStream inputStream = client.makeFinalRequestForFile(method, httpFile, true);
if (inputStream != null) {
logger.info("Saving to file");
downloadTask.saveToFile(inputStream);
return true;
} else {
logger.info("Saving file failed");
return false;
}
} finally {
method.abort();
method.releaseConnection();
}
}
示例13: toPostMethod
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
/**
* Returns result POST method.<br/>
* Result POST method is composed by baseURL + action (if baseURL is not null).<br/>
* All parameters are set and encoded.
* At least one of the parameter has to be not null and the string has to start with 'http'.
*
* @return new instance of HttpMethod with POST request
* @throws BuildMethodException if something goes wrong
*/
public HttpMethod toPostMethod() throws BuildMethodException {
if (referer != null)
client.setReferer(referer);
String s = generateURL();
if (encodePathAndQuery)
try {
s = URIUtil.encodePathQuery(s, encoding);
} catch (URIException e) {
throw new BuildMethodException("Cannot create URI");
}
s = checkURI(s);
final PostMethod postMethod = client.getPostMethod(s);
for (Map.Entry<String, String> entry : parameters.entrySet()) {
postMethod.addParameter(entry.getKey(), (encodeParameters) ? encode(entry.getValue()) : entry.getValue());
}
setAdditionalHeaders(postMethod);
return postMethod;
}
示例14: assertPostStatus
import org.apache.commons.httpclient.HttpMethod; //导入依赖的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
示例15: downloadPacContent
import org.apache.commons.httpclient.HttpMethod; //导入依赖的package包/类
private String downloadPacContent(String url) throws IOException {
if (url == null) {
Engine.logProxyManager.debug("(PacManager) Invalid PAC script URL: null");
throw new IOException("Invalid PAC script URL: null");
}
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
throw new IOException("(PacManager) Method failed: " + method.getStatusLine());
}
return IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8");
}