本文整理匯總了Java中org.apache.commons.httpclient.HttpClient.executeMethod方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpClient.executeMethod方法的具體用法?Java HttpClient.executeMethod怎麽用?Java HttpClient.executeMethod使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.apache.commons.httpclient.HttpClient
的用法示例。
在下文中一共展示了HttpClient.executeMethod方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: get
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的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: chcekConnectionStatus
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
public void chcekConnectionStatus() throws IOException {
HttpClient httpClient = new HttpClient();
//TODO : add connection details while testing only,remove it once done
String teradatajson = "{\"username\":\"\",\"password\":\"\",\"hostname\":\"\",\"database\":\"\",\"dbtype\":\"\",\"port\":\"\"}";
PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/getConnectionStatus");
//postMethod.addParameter("request_parameters", redshiftjson);
postMethod.addParameter("request_parameters", teradatajson);
int response = httpClient.executeMethod(postMethod);
InputStream inputStream = postMethod.getResponseBodyAsStream();
byte[] buffer = new byte[1024 * 1024 * 5];
String path = null;
int length;
while ((length = inputStream.read(buffer)) > 0) {
path = new String(buffer);
}
System.out.println("Response of service: " + path);
System.out.println("==================");
}
示例3: getUrlContent
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
/**
* Retrieves the content under the given URL with username and passwort
* authentication.
*
* @param url
* the URL to read
* @param username
* @param password
* @return the read content.
* @throws IOException
* if an I/O exception occurs.
*/
private static byte[] getUrlContent(URL url, String username,
String password) throws IOException {
final HttpClient client = new HttpClient();
// Set credentials:
client.getParams().setAuthenticationPreemptive(true);
final Credentials credentials = new UsernamePasswordCredentials(
username, password);
client.getState()
.setCredentials(
new AuthScope(url.getHost(), url.getPort(),
AuthScope.ANY_REALM), credentials);
// Retrieve content:
final GetMethod method = new GetMethod(url.toString());
final int status = client.executeMethod(method);
if (status != HttpStatus.SC_OK) {
throw new IOException("Error " + status + " while retrieving "
+ url);
}
return method.getResponseBody();
}
示例4: httpClientPost
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) {
String result = "";
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
try {
NameValuePair[] params = new NameValuePair[list.size()];
for (int i = 0; i < list.size(); i++) {
params[i] = list.get(i);
}
postMethod.addParameters(params);
client.executeMethod(postMethod);
result = postMethod.getResponseBodyAsString();
} catch (Exception e) {
logger.error(e);
} finally {
postMethod.releaseConnection();
}
return result;
}
示例5: httpClient3Test
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的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";
}
示例6: getData
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的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 ();
}
}
示例7: execWithDebugOutput
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
/**
* Execute the request with the request and response logged at debug level
* @param method method to execute
* @param client client to use
* @param <M> method type
* @return the status code
* @throws IOException any failure reported by the HTTP client.
*/
private <M extends HttpMethod> int execWithDebugOutput(M method,
HttpClient client) throws
IOException {
if (LOG.isDebugEnabled()) {
StringBuilder builder = new StringBuilder(
method.getName() + " " + method.getURI() + "\n");
for (Header header : method.getRequestHeaders()) {
builder.append(header.toString());
}
LOG.debug(builder);
}
int statusCode = client.executeMethod(method);
if (LOG.isDebugEnabled()) {
LOG.debug("Status code = " + statusCode);
}
return statusCode;
}
示例8: main
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
HttpClient client = new HttpClient();
// pass our credentials to HttpClient, they will only be used for
// authenticating to servers with realm "realm" on the host
// "www.verisign.com", to authenticate against
// an arbitrary realm or host change the appropriate argument to null.
client.getState().setCredentials(
new AuthScope("www.verisign.com", 443, "realm"),
new UsernamePasswordCredentials("username", "password")
);
// create a GET method that reads a file over HTTPS, we're assuming
// that this file requires basic authentication using the realm above.
GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");
// Tell the GET method to automatically handle authentication. The
// method will use any appropriate credentials to handle basic
// authentication requests. Setting this value to false will cause
// any request for authentication to return with a status of 401.
// It will then be up to the client to handle the authentication.
get.setDoAuthentication( true );
try {
// execute the GET
int status = client.executeMethod( get );
// print the status and response
System.out.println(status + "\n" + get.getResponseBodyAsString());
} finally {
// release any connection resources used by the method
get.releaseConnection();
}
}
示例9: getResponse
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
private MCRContent getResponse(String queryURL) throws HttpException, IOException {
//prepare http client
HttpClient client = new HttpClient();
//prepare GET-request
connection = new GetMethod(queryURL);
//execute request, get response from API and return as stream
client.executeMethod(connection);
InputStream response = connection.getResponseBodyAsStream();
return new MCRStreamContent(response);
}
示例10: getResponse
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
public MCRStreamContent getResponse(String queryURL) throws IOException {
//prepare http client
HttpClient client = new HttpClient();
//prepare GET-request
connection = new GetMethod(queryURL);
//execute request, get response from API and return as stream
client.executeMethod(connection);
InputStream response = connection.getResponseBodyAsStream();
return new MCRStreamContent(response);
}
示例11: main
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Usage: ChunkEncodedPost <file>");
System.out.println("<file> - full path to a file to be posted");
System.exit(1);
}
HttpClient client = new HttpClient();
PostMethod httppost = new PostMethod("http://localhost:8080/httpclienttest/body");
File file = new File(args[0]);
httppost.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file)));
httppost.setContentChunked(true);
try {
client.executeMethod(httppost);
if (httppost.getStatusCode() == HttpStatus.SC_OK) {
System.out.println(httppost.getResponseBodyAsString());
} else {
System.out.println("Unexpected failure: " + httppost.getStatusLine().toString());
}
} finally {
httppost.releaseConnection();
}
}
示例12: executeQuery
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
private HttpMethod executeQuery(FederatedSearch sruSearch, String query, SRUSettings settings, int offset,
int perpage) throws IOException
{
HttpMethod httpMethod = null;
try
{
// URL includes the port (if any) we trust ...
URL url = new URL(settings.getUrl());
PostMethod postMethod = new PostMethod(url.toExternalForm());
NameValuePair[] nameValuePairs = populateNameValuePairs(query, settings, offset, perpage);
postMethod.addParameters(nameValuePairs);
httpMethod = postMethod;
}
catch( Exception e )
{
throw new RuntimeException(e);
}
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(sruSearch.getTimeout() * 1000);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(sruSearch.getTimeout() * 1000);
// Prevent the default 3 tries - so once is enough ...?
httpClient.getHttpConnectionManager().getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(0, false));
httpClient.executeMethod(httpMethod);
return httpMethod;
}
示例13: main
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
/**
*
* Usage:
* java PostXML http://mywebserver:80/ c:\foo.xml
*
* @param args command line arguments
* Argument 0 is a URL to a web server
* Argument 1 is a local filename
*
*/
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Usage: java -classpath <classpath> [-Dorg.apache.commons.logging.simplelog.defaultlog=<loglevel>] PostXML <url> <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("<filename> - file to post to the URL");
System.out.println();
System.exit(1);
}
// Get target URL
String strURL = args[0];
// Get file to be posted
String strXMLFilename = args[1];
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);
// 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();
}
}
示例14: calltoFilterService
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
public void calltoFilterService() throws IOException {
HttpClient httpClient = new HttpClient();
// String json =
// "{\"condition\":\"abc\",\"schema\":[{\"fieldName\":\"f1\",\"dateFormat\":\"\",\"dataType\":\"1\",\"scale\":\"scale\",\"dataTypeValue\":\"java.lang.String\",\"scaleType\":1,\"scaleTypeValue\":\"scaleTypeValue\",\"precision\":\"precision\",\"description\":\"description\"},{\"fieldName\":\"f2\",\"dateFormat\":\"\",\"dataType\":1,\"scale\":\"scale\",\"dataTypeValue\":\"java.util.Date\",\"scaleType\":1,\"scaleTypeValue\":\"scaleTypeValue\",\"precision\":\"precision\",\"description\":\"description\"},{\"fieldName\":\"f3\",\"dateFormat\":\"\",\"dataType\":1,\"scale\":\"scale\",\"dataTypeValue\":\"java.util.Date\",\"scaleType\":1,\"scaleTypeValue\":\"scaleTypeValue\",\"precision\":\"precision\",\"description\":\"description\"},{\"fieldName\":\"f4\",\"dateFormat\":\"\",\"dataType\":1,\"scale\":\"scale\",\"dataTypeValue\":\"java.math.BigDecimal\",\"scaleType\":1,\"scaleTypeValue\":\"scaleTypeValue\",\"precision\":\"precision\",\"description\":\"description\"}],\"fileSize\":1,\"jobDetails\":{\"host\":\"127.0.0.1\",\"port\":\"8005\",\"username\":\"hduser\",\"password\":\"Bitwise2012\",\"basepath\":\"C:/Users/santlalg/git/Hydrograph/hydrograph.engine/hydrograph.engine.command-line\",\"uniqueJobID\":\"debug_job\",\"componentID\":\"input\",\"componentSocketID\":\"out0\",\"isRemote\":false}}";
String json = "{\"condition\":\"(f1 LIKE 'should')\",\"schema\":[{\"fieldName\":\"f1\",\"dateFormat\":\"\",\"dataType\":\"1\",\"scale\":\"scale\",\"dataTypeValue\":\"java.lang.String\",\"scaleType\":1,\"scaleTypeValue\":\"scaleTypeValue\",\"precision\":\"precision\",\"description\":\"description\"},{\"fieldName\":\"f2\",\"dateFormat\":\"\",\"dataType\":1,\"scale\":\"scale\",\"dataTypeValue\":\"java.util.Date\",\"scaleType\":1,\"scaleTypeValue\":\"scaleTypeValue\",\"precision\":\"precision\",\"description\":\"description\"},{\"fieldName\":\"f3\",\"dateFormat\":\"\",\"dataType\":1,\"scale\":\"scale\",\"dataTypeValue\":\"java.lang.Float\",\"scaleType\":1,\"scaleTypeValue\":\"scaleTypeValue\",\"precision\":\"precision\",\"description\":\"description\"},{\"fieldName\":\"f4\",\"dateFormat\":\"\",\"dataType\":1,\"scale\":\"scale\",\"dataTypeValue\":\"java.lang.Double\",\"scaleType\":1,\"scaleTypeValue\":\"scaleTypeValue\",\"precision\":\"precision\",\"description\":\"description\"}],\"fileSize\":"
+ FILE_SIZE_TO_READ + ",\"jobDetails\":{\"host\":\"" + HOST_NAME + "\",\"port\":\"" + PORT
+ "\",\"username\":\"" + USER_ID + "\",\"password\":\"" + PASSWORD + "\",\"basepath\":\"" + BASE_PATH
+ "\",\"uniqueJobID\":\"" + JOB_ID + "\",\"componentID\":\"" + COMPONENT_ID
+ "\",\"componentSocketID\":\"" + SOCKET_ID + "\",\"isRemote\":false}}";
PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/filter");
postMethod.addParameter("request_parameters", json);
int response = httpClient.executeMethod(postMethod);
InputStream inputStream = postMethod.getResponseBodyAsStream();
byte[] buffer = new byte[1024 * 1024 * 5];
String path = null;
int length;
while ((length = inputStream.read(buffer)) > 0) {
path = new String(buffer);
}
System.out.println("response of service: " + path);
}
示例15: makeRestCallPost
import org.apache.commons.httpclient.HttpClient; //導入方法依賴的package包/類
public MirrorGateResponse makeRestCallPost(String url, String jsonString, String user, String password) {
MirrorGateResponse response;
PostMethod post = new PostMethod(url);
try {
HttpClient client = getHttpClient();
if (user != null && password != null) {
client.getState().setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(user, password));
post.setDoAuthentication(true);
}
StringRequestEntity requestEntity = new StringRequestEntity(
jsonString,
"application/json",
"UTF-8");
post.setRequestEntity(requestEntity);
int responseCode = client.executeMethod(post);
String responseString = post.getResponseBodyAsStream() != null ?
getResponseString(post.getResponseBodyAsStream()) : "";
response = new MirrorGateResponse(responseCode, responseString);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "MirrorGate: Error posting to MirrorGate", e);
response = new MirrorGateResponse(HttpStatus.SC_BAD_REQUEST, "");
} finally {
post.releaseConnection();
}
return response;
}