List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:au.org.ala.spatial.util.UploadSpatialResource.java
public static String loadCreateStyle(String url, String extra, String username, String password, String name) { System.out.println("loadCreateStyle url:" + url); System.out.println("name:" + name); String output = ""; HttpClient client = new HttpClient(); client.setConnectionTimeout(10000);/* www . j a v a 2s.c om*/ client.setTimeout(60000); client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); PostMethod post = new PostMethod(url); post.setDoAuthentication(true); // Execute the request try { // Request content will be retrieved directly // from the input stream File file = File.createTempFile("sld", "xml"); FileWriter fw = new FileWriter(file); fw.append("<style><name>" + name + "</name><filename>" + name + ".sld</filename></style>"); fw.close(); RequestEntity entity = new FileRequestEntity(file, "text/xml"); post.setRequestEntity(entity); int result = client.executeMethod(post); output = result + ": " + post.getResponseBodyAsString(); } catch (Exception e) { e.printStackTrace(System.out); output = "0: " + e.getMessage(); } finally { // Release current connection to the connection pool once you are done post.releaseConnection(); } return output; }
From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java
public static InputStream executeAnyAQLAsync(String str, boolean defer, OutputFormat fmt) throws Exception { final String url = "http://localhost:19002/aql"; // Create a method instance. PostMethod method = new PostMethod(url); if (defer) {/*from ww w .j av a 2 s . c o m*/ method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous-deferred") }); } else { method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous") }); } method.setRequestEntity(new StringRequestEntity(str)); method.setRequestHeader("Accept", fmt.mimeType()); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); executeHttpMethod(method); InputStream resultStream = method.getResponseBodyAsStream(); String theHandle = IOUtils.toString(resultStream, "UTF-8"); //take the handle and parse it so results can be retrieved InputStream handleResult = getHandleResult(theHandle, fmt); return handleResult; }
From source file:it.intecs.pisa.develenv.model.launch.ToolboxScriptRunLaunch.java
protected static InputStream sendFile(String url, String soapAction, InputStream stream) throws FileNotFoundException, IOException, HttpException { PostMethod post; int result;// w w w . j ava2 s . c o m MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpClient client = new HttpClient(connectionManager); post = new PostMethod(url); post.setRequestEntity(new InputStreamRequestEntity(stream, "text/xml")); post.setRequestHeader("soapaction", soapAction); result = client.executeMethod(post); InputStream in = post.getResponseBodyAsStream(); return in; }
From source file:fr.cls.atoll.motu.processor.wps.framework.WPSUtils.java
/** * Performs an HTTP-Get request and provides typed access to the response. * //from w w w . j ava 2s .co m * @param <T> * @param worker * @param url * @param postBody * @param headers * @return some object from the url * @throws HttpException * @throws IOException * @throws MotuException */ public static <T> T post(Worker<T> worker, String url, InputStream postBody, Map<String, String> headers) throws HttpException, IOException, MotuException { if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - start"); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(postBody, out); } finally { IOUtils.closeQuietly(out); } InputStream postBodyCloned = new ByteArrayInputStream(out.toString().getBytes()); MultiThreadedHttpConnectionManager connectionManager = HttpUtil.createConnectionManager(); HttpClientCAS client = new HttpClientCAS(connectionManager); HttpClientParams clientParams = new HttpClientParams(); //clientParams.setParameter("http.protocol.allow-circular-redirects", true); //HttpClientParams.ALLOW_CIRCULAR_REDIRECTS client.setParams(clientParams); PostMethod post = new PostMethod(url); post.getParams().setCookiePolicy(CookiePolicy.RFC_2109); InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(postBody); post.setRequestEntity(inputStreamRequestEntity); for (String key : headers.keySet()) { post.setRequestHeader(key, headers.get(key)); } String query = post.getQueryString(); // Check redirection // DONT USE post.setFollowRedirects(true); see http://hc.apache.org/httpclient-3.x/redirects.html int httpReturnCode = client.executeMethod(post); if (LOG.isDebugEnabled()) { String msg = String.format("Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } if (httpReturnCode == 302) { post.releaseConnection(); String redirectLocation = null; Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); if (!WPSUtils.isNullOrEmpty(redirectLocation)) { if (LOG.isDebugEnabled()) { String msg = String.format("Query is redirected to url: '%s'", redirectLocation); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } post = new PostMethod(url); post.setRequestEntity(new InputStreamRequestEntity(postBodyCloned)); // Recrire un nouveau InputStream for (String key : headers.keySet()) { post.setRequestHeader(key, headers.get(key)); } clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, false); httpReturnCode = client.executeMethod(post); clientParams.setBooleanParameter(HttpClientCAS.ADD_CAS_TICKET_PARAM, true); if (LOG.isDebugEnabled()) { String msg = String.format( "Executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end - " + msg); } } } } T returnValue = worker.work(post.getResponseBodyAsStream()); if (httpReturnCode >= 400) { if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end"); } String msg = String.format( "Error while executing the query:\n==> http code: '%d':\n==> url: '%s'\n==> body:\n'%s'", httpReturnCode, url, query); throw new MotuException(msg); } if (LOG.isDebugEnabled()) { LOG.debug("post(Worker<T>, String, InputStream, Map<String,String>) - end"); } return returnValue; }
From source file:cn.newtouch.util.HttpClientUtil.java
/** * //ww w . j a v a2s . co m * * * @since 2012-1-8 * @param url * URL?URL? * @param file * * @param fileFieldName * forminputname * * @param params * ??? * @throws Exception */ public static void uploadFile(String url, File file, String fileFieldName, Map<String, String> params) throws Exception { String targetURL = url;// URL File targetFile = file;// PostMethod filePost = new PostMethod(targetURL); try { List<StringPart> strPartList = new ArrayList<StringPart>(); // ??? Set<String> keys = params.keySet(); for (String key : keys) { StringPart sp = new StringPart(key, params.get(key), "utf-8"); strPartList.add(sp); } Part[] parts = new Part[1 + strPartList.size()]; parts[0] = new FilePart(fileFieldName, targetFile); for (int i = 0; i < strPartList.size(); i++) { parts[i + 1] = strPartList.get(i); } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { System.out.println("?"); // ? } else { System.out.println(""); throw new Exception("?" + status); // } } catch (Exception e) { e.printStackTrace(); throw new Exception("" + e.getMessage()); } finally { filePost.releaseConnection(); } }
From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java
private static void freeCgiAsyncResources(String endpoint, EndpointReference epr) throws MobyException { // construct the Httpclient HttpClient client = new HttpClient(); client.getParams().setParameter("http.useragent", "jMoby/Taverna2"); // create the post method PostMethod method = new PostMethod(endpoint + "/destroy"); // put our data in the request RequestEntity entity;/* w ww .ja va 2s . c o m*/ try { entity = new StringRequestEntity("<Destroy xmlns=\"http://docs.oasis-open.org/wsrf/rl-2\"/>", "text/xml", null); } catch (UnsupportedEncodingException e) { throw new MobyException("Problem posting data to webservice", e); } method.setRequestEntity(entity); // set the header StringBuffer httpheader = new StringBuffer(); httpheader.append("<moby-wsrf>"); httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">" + DESTROY_RESOURCE_ACTION + "</wsa:Action>"); httpheader.append( "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">" + endpoint + "</wsa:To>"); httpheader.append( "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">" + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>"); httpheader.append("</moby-wsrf>"); method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", "")); // retry up to 10 times client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(10, true)); // call the method try { int result = client.executeMethod(method); if (result != HttpStatus.SC_OK) throw new MobyException( "Async HTTP POST service returned code: " + result + "\n" + method.getStatusLine()); } catch (IOException e) { throw new MobyException("Problem reading response from webservice", e); } finally { // Release current connection to the connection pool once you are // done method.releaseConnection(); } }
From source file:modnlp.capte.AlignerUtils.java
@SuppressWarnings("deprecation") /* This method creates the HTTP connection to the server * and sends the POST request with the two files for alignment, * //from www. j av a 2s . c o m * The server returns the aligned file as the response to the post request, * which is delimited by the tag <beginalignment> which separates the file * from the rest of the POST request * * * */ public static String MultiPartFileUpload(String source, String target) throws IOException { String response = ""; String serverline = System.getProperty("capte.align.server"); //"http://ronaldo.cs.tcd.ie:80/~gplynch/aling.cgi"; PostMethod filePost = new PostMethod(serverline); // Send any XML file as the body of the POST request File f1 = new File(source); File f2 = new File(target); System.out.println(f1.getName()); System.out.println(f2.getName()); System.out.println("File1 Length = " + f1.length()); System.out.println("File2 Length = " + f2.length()); Part[] parts = { new StringPart("param_name", "value"), new FilePart(f2.getName(), f2), new FilePart(f1.getName(), f1) }; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); int status = client.executeMethod(filePost); String res = ""; InputStream is = filePost.getResponseBodyAsStream(); Header[] heads = filePost.getResponseHeaders(); Header[] feet = filePost.getResponseFooters(); BufferedInputStream bis = new BufferedInputStream(is); String datastr = null; StringBuffer sb = new StringBuffer(); byte[] bytes = new byte[8192]; // reading as chunk of 8192 int count = bis.read(bytes); while (count != -1 && count <= 8192) { datastr = new String(bytes, "UTF8"); sb.append(datastr); count = bis.read(bytes); } bis.close(); res = sb.toString(); System.out.println("----------------------------------------"); System.out.println("Status is:" + status); //System.out.println(res); /* for debugging for(int i = 0 ;i < heads.length ;i++){ System.out.println(heads[i].toString()); } for(int j = 0 ;j < feet.length ;j++){ System.out.println(feet[j].toString()); } */ filePost.releaseConnection(); String[] handle = res.split("<beginalignment>"); //Check for errors in the header // System.out.println(handle[0]); //Return the required text String ho = ""; if (handle.length < 2) { System.out.println("Server error during alignment, check file encodings"); ho = "error"; } else { ho = handle[1]; } return ho; }
From source file:com.ebt.platform.utility.WebServiceCaller.java
public static String CallERPWebService(String xml, String webservicePath) { PostMethod postMethod = new PostMethod(webservicePath); String responseString = null; try {//from w w w. j a v a 2s . co m byte[] b = xml.getBytes("utf-8"); InputStream inS = new ByteArrayInputStream(b, 0, b.length); RequestEntity req = new InputStreamRequestEntity(inS, b.length, "text/xml; charset=utf-8"); postMethod.setRequestEntity(req); HttpClient httpClient = new HttpClient(); int statusCode = httpClient.executeMethod(postMethod); if (statusCode == 200) { responseString = new String(postMethod.getResponseBodyAsString().getBytes("ISO-8859-1"), "UTF-8"); System.out.println("WebService??====" + responseString); } else { System.out.println("WebService??" + statusCode); } } catch (Exception e) { e.printStackTrace(); } return responseString; }
From source file:com.tops.hotelmanager.util.CommonHttpClient.java
private static String executePOSTRequestV1(String url, Map<String, Object> requestData, Map<String, String> headerMap, String contentType, int timeOut, int retry) { PostMethod post = new PostMethod(url); Gson gson = new Gson(); String errorMsg = "error~Request Failed"; try {/*from w w w .j a v a2 s .c o m*/ HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setSoTimeout(timeOut); client.getHttpConnectionManager().getParams().setConnectionTimeout(timeOut); if (requestData == null || requestData.isEmpty()) { throw new CustomException("Request data is null"); } if (contentType != null && contentType.equals(CommonHttpClient.CONTENT_TYPE_JSON)) { StringRequestEntity requestEntity = new StringRequestEntity(gson.toJson(requestData), contentType, "UTF-8"); post.setRequestEntity(requestEntity); } else { // SET REQUEST PARAMETER for (Map.Entry<String, Object> entry : requestData.entrySet()) { post.addParameter(entry.getKey(), String.valueOf(entry.getValue())); } } // SET REQUEST HEADER if (headerMap != null) { for (Map.Entry<String, String> entry : headerMap.entrySet()) { post.addRequestHeader(entry.getKey(), entry.getValue()); } } int status = client.executeMethod(post); // System.out.println("URL:" + url); // System.out.println("\n REQUEST HEADERS:"); // Header[] requestHeaders = post.getRequestHeaders(); // for (Header header : requestHeaders) { // System.out.println(header.getName() + "=" + header.getValue()); // } // System.out.println("\n RESPONSE HEADERS:"); // Header[] responseHeaders = post.getResponseHeaders(); // for (Header header : responseHeaders) { // System.out.println(header.getName() + "=" + header.getValue()); // } // System.out.println(post.getStatusText()); // System.out.println(post.getStatusLine().getReasonPhrase()); // System.out.println(post.getResponseBodyAsString()); if (status == HttpStatus.SC_OK) { return post.getResponseBodyAsString(); } else if (status == HttpStatus.SC_TEMPORARY_REDIRECT) { Header header = post.getResponseHeader("Location"); if (retry != 1) { errorMsg = executePOSTRequestV1(header.getValue(), requestData, headerMap, contentType, timeOut, retry++); } } else { errorMsg += ",HttpStatus:" + status; } } catch (Exception ex) { logger.error("executePOSTRequestV1 url: " + url + ", Parameters: " + requestData, ex); errorMsg = errorMsg + ":" + ex.getMessage(); } finally { post.releaseConnection(); } return errorMsg; }
From source file:com.ebt.platform.utility.WebServiceCaller.java
public static String CallUacWebService(String xml) { PostMethod postMethod = new PostMethod("http://UACServer.e-bao.cn:8086/UACService.asmx"); String responseString = null; try {/* ww w.j a v a2 s . com*/ byte[] b = xml.getBytes("utf-8"); InputStream inS = new ByteArrayInputStream(b, 0, b.length); RequestEntity req = new InputStreamRequestEntity(inS, b.length, "text/xml; charset=utf-8"); postMethod.setRequestEntity(req); HttpClient httpClient = new HttpClient(); int statusCode = httpClient.executeMethod(postMethod); if (statusCode == 200) { responseString = new String(postMethod.getResponseBodyAsString().getBytes("ISO-8859-1"), "UTF-8"); System.out.println("WebService??====" + responseString); } else { System.out.println("WebService??" + statusCode); } } catch (Exception e) { e.printStackTrace(); } return responseString; }