List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod
public PostMethod(String paramString)
From source file:edu.unc.lib.dl.cdr.sword.server.test.DepositClientsByHand.java
@Test public void testUpload() throws Exception { String user = ""; String password = ""; String pid = "uuid:c9aba0a2-12e9-4767-822e-b285a37b07d7"; String payloadMimeType = "text/xml"; String payloadPath = "src/test/resources/dcDocument.xml"; String metadataPath = "src/test/resources/atompubMODS.xml"; String depositPath = "https://localhost:444/services/sword/collection/"; String testSlug = "ingesttestslug"; HttpClient client = HttpClientUtil.getAuthenticatedClient(depositPath + pid, user, password); client.getParams().setAuthenticationPreemptive(true); PostMethod post = new PostMethod(depositPath + pid); File payload = new File(payloadPath); File atom = new File(metadataPath); FilePart payloadPart = new FilePart("payload", payload); payloadPart.setContentType(payloadMimeType); payloadPart.setTransferEncoding("binary"); Part[] parts = { payloadPart, new FilePart("atom", atom, "application/atom+xml", "utf-8") }; MultipartRequestEntity mpEntity = new MultipartRequestEntity(parts, post.getParams()); String boundary = mpEntity.getContentType(); boundary = boundary.substring(boundary.indexOf("boundary=") + 9); Header header = new Header("Content-type", "multipart/related; type=application/atom+xml; boundary=" + boundary); post.addRequestHeader(header);/*from ww w . j a v a 2 s . c o m*/ Header slug = new Header("Slug", testSlug); post.addRequestHeader(slug); post.setRequestEntity(mpEntity); LOG.debug("" + client.executeMethod(post)); }
From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java
/** * //from w w w . ja va 2 s . c om * */ public static int invoke(URL url, String userName, String password, Map<String, String> headers, InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout, int soTimeout) throws IOException, SocketTimeoutException { HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url); SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true); manager.getParams().setConnectionTimeout(connectionTimeout); manager.getParams().setSoTimeout(soTimeout); manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2); client.setHttpConnectionManager(manager); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); PostMethod method = new PostMethod(url.getFile()); method.setRequestEntity(new InputStreamRequestEntity(input)); for (Map.Entry<String, String> e : headers.entrySet()) { method.addRequestHeader(e.getKey(), e.getValue()); } if (!headers.containsKey("Content-Type")) method.addRequestHeader("Content-Type", "text/xml; charset=utf-8"); if (!headers.containsKey("Accept")) method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*"); if (!headers.containsKey("SOAPAction")) method.addRequestHeader("SOAPAction", "\"\""); if (!headers.containsKey("User-Agent")) method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0"); if (userName != null) { int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); if (port == -1) { port = 80; } } if (password == null) { password = ""; } client.getState().setCredentials(new AuthScope(url.getHost(), port, null), new UsernamePasswordCredentials(userName, password)); client.getParams().setAuthenticationPreemptive(true); method.setDoAuthentication(true); } try { int status; try { status = client.executeMethod(method); } catch (SocketTimeoutException e) { status = HttpServletResponse.SC_REQUEST_TIMEOUT; } output.setStatus(status); if (status == 200) { for (Header h : method.getResponseHeaders()) { String name = h.getName(); if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase()))) continue; String value = h.getValue(); output.addHeader(name, value); } OutputStream os = output.getOutputStream(); StreamUtil.transfer(method.getResponseBodyAsStream(), os); os.flush(); } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) { } else { StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut); } return status; } finally { manager.shutdown(); } }
From source file:de.sones.mule.demo.transformers.GQLToHttpRequestTransformer.java
@Override public Object transformMessage(MuleMessage message, String arg1) throws TransformerException { try {//from w w w.ja v a2s . c o m HttpMethod result; //Get the contents of the previous message Object src = message.getPayload(); System.out.println("Body:" + src.toString()); //Get the endpoint which is configured String endpoint = message.getOutboundProperty(MuleProperties.MULE_ENDPOINT_PROPERTY, null); System.out.println("Enpoint:" + endpoint); //Create an uri URI uri = null; uri = new URI(endpoint); PostMethod postMethod = new PostMethod(uri.toString()); InputStream is = new ByteArrayInputStream(src.toString().getBytes("UTF-8")); postMethod.setRequestBody(src.toString()); result = postMethod; return result; } catch (Exception e) { throw new TransformerException(this, e); } }
From source file:com.nokia.carbide.internal.bugreport.model.Communication.java
/** * Sends given fields as a bug_report to the server provided by product. * @param fields values which are sent to the server * @param product product provides e.g. server URL * @return bug_id of the added bug_entry * @throws RuntimeException if an error occurred. Error can be either some communication error * or error message provided by the server (e.g. invalid password) *//*w w w.j av a 2s.com*/ public static String sendBugReport(Hashtable<String, String> fields, IProduct product) throws RuntimeException { // Nothing to send if (fields == null || fields.size() < 1) { throw new RuntimeException(Messages.getString("Communication.NothingToSend")); //$NON-NLS-1$ } String bugNumber = ""; //$NON-NLS-1$ String url = product.getUrl(); if (url.startsWith("https")) { //$NON-NLS-1$ // we'll support HTTPS with trusted (i.e. signed) certificates // Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); //$NON-NLS-1$ //$NON-NLS-2$ } PostMethod filePost = new PostMethod(url); Part[] parts = new Part[fields.size()]; int i = 0; Iterator<Map.Entry<String, String>> it = fields.entrySet().iterator(); // create parts while (it.hasNext()) { Map.Entry<String, String> productField = it.next(); // attachment field if (productField.getKey() == FieldsHandler.FIELD_ATTACHMENT) { File f = new File(productField.getValue()); try { parts[i] = new FilePart(FieldsHandler.FIELD_DATA, f); } catch (FileNotFoundException e) { e.printStackTrace(); parts[i] = new StringPart(FieldsHandler.FIELD_DATA, Messages.getString("Communication.NotFound")); //$NON-NLS-1$ } // string field } else { parts[i] = new StringPart(productField.getKey(), productField.getValue()); } i++; } filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(8000); setProxyData(client, filePost); int status = 0; String receivedData = ""; //$NON-NLS-1$ try { status = client.executeMethod(filePost); receivedData = filePost.getResponseBodyAsString(1024 * 1024); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } finally { filePost.releaseConnection(); } // HTTP status codes: 2xx = Success if (status >= 200 && status < 300) { // some error occurred in the server side (e.g. invalid password) if (receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR) && receivedData.contains(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE)) { int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR) + FieldsHandler.TAG_RESPONSE_ERROR.length(); int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_ERROR_CLOSE); String error = receivedData.substring(beginIndex, endIndex); error = error.trim(); throw new RuntimeException(error); // bug_entry was added successfully to database, read the bug_number } else if (receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID) && receivedData.contains(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE)) { int beginIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID) + FieldsHandler.TAG_RESPONSE_BUG_ID.length(); int endIndex = receivedData.indexOf(FieldsHandler.TAG_RESPONSE_BUG_ID_CLOSE); bugNumber = receivedData.substring(beginIndex, endIndex); bugNumber = bugNumber.trim(); // some unknown error } else { throw new RuntimeException(Messages.getString("Communication.UnknownError")); //$NON-NLS-1$ } // some HTTP error (status code other than 2xx) } else { String error = Messages.getString("Communication.HttpError") + status; //$NON-NLS-1$ throw new RuntimeException(error); } return bugNumber; }
From source file:net.sourceforge.jwbf.actions.mw.login.PostLoginOld.java
/** * //from ww w . ja v a 2 s . c o m * @param username * the * @param pw * password */ public PostLoginOld(final String username, final String pw, final String domain) { this.username = username; NameValuePair action = new NameValuePair("wpLoginattempt", "Log in"); NameValuePair url = new NameValuePair("wpRemember", "1"); NameValuePair userid = new NameValuePair("wpName", username); NameValuePair dom = new NameValuePair("wpDomain", domain); String pwLabel = "wpPassword"; NameValuePair password = new NameValuePair(pwLabel, pw); PostMethod pm = new PostMethod("/index.php?title=Special:Userlogin&action=submitlogin&type=login"); pm.getParams().setContentCharset(MediaWikiBot.CHARSET); pm.setRequestBody(new NameValuePair[] { action, url, userid, dom, password }); msgs.add(pm); }
From source file:net.morphbank.webclient.RemoteImageProcessing.java
public void sendImage(String strURL, String id, String originalFileName, String imageFileName) throws Exception { File input = new File(imageFileName); // Prepare HTTP post PostMethod post = new PostMethod(strURL); Part[] parts = { new StringPart("id", id), new StringPart("fileName", originalFileName), new FilePart("image", originalFileName, input) }; RequestEntity entity = new MultipartRequestEntity(parts, post.getParams()); post.setRequestEntity(entity);/*from w w w .j av a 2 s . c o m*/ // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { System.out.println("Trying post"); int postStatus = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + postStatus); // Display response System.out.print("Response body: "); InputStream response = post.getResponseBodyAsStream(); for (int i = response.read(); i != -1; i = response.read()) { System.out.write(i); } System.out.flush(); } finally { // Release current connection to the connection pool once you are // done post.releaseConnection(); } }
From source file:com.ironiacorp.http.impl.httpclient3.PostRequest.java
public HttpJob call() { URI uri = (URI) job.getUri(); PostMethod postMethod = new PostMethod(uri.toString()); HttpMethodResult result = new HttpMethodResult(); postMethod.setRequestBody(parameters.toArray(new NameValuePair[0])); try {/*from w ww. j a va2 s . c o m*/ int statusCode = client.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); } InputStream inputStream = postMethod.getResponseBodyAsStream(); if (inputStream != null) { result.setContent(inputStream); result.setStatusCode(statusCode); job.setResult(result); } } catch (HttpException e) { } catch (IOException e) { // In case of an IOException the connection will be released // back to the connection manager automatically } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. postMethod.abort(); } return job; }
From source file:de.lohndirekt.print.IppHttpConnection.java
/** * @param uri//from w ww . j a v a 2 s .co m * @param user * @param passwd * @param useStream */ public IppHttpConnection(URI uri, String user, String passwd) { try { httpConn = new HttpClient(); method = new PostMethod(toHttpURI(uri).toString()); method.addRequestHeader("Content-type", "application/ipp"); method.addRequestHeader("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"); method.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_AUTO); // authentication if (user != null && user.trim().length() > 0) { if (log.isLoggable(Level.FINER)) { log.log(Level.SEVERE, "Using username: " + user + " , passwd.length " + passwd.length()); } method.setDoAuthentication(true); Credentials creds = new UsernamePasswordCredentials(user, passwd); httpConn.getState().setCredentials(null, toHttpURI(uri).getHost(), creds); } } catch (Exception e) { log.log(Level.SEVERE, e.getMessage(), e); } }
From source file:cn.edu.seu.herald.auth.AuthenticationServiceImpl.java
@Override public StudentUser authenticate(String username, String password) throws AuthenticationServiceException { PostMethod post = new PostMethod(baseUri); post.setQueryString(new NameValuePair[] { new NameValuePair(PARAM_USER, username), new NameValuePair(PARAM_PASS, password) }); try {//ww w . j av a2s . co m int statusCode = httpClient.executeMethod(post); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { return null; } if (statusCode != HttpStatus.SC_OK) { throw new AuthenticationServiceException("Unexpected status: " + statusCode); } String csv = post.getResponseBodyAsString(); String values[] = csv.split(","); if (values == null || values.length != 2) { throw new AuthenticationServiceException( String.format("%s\n%s\n", "Unexpected server response:\n", csv)); } String name = values[0]; String cardNumber = values[1]; return new StudentUser(name, cardNumber); } catch (IOException ex) { throw new AuthenticationServiceException(ex); } finally { post.releaseConnection(); } }
From source file:it.drwolf.ridire.utility.test.SSLConnectionTest.java
public SSLConnectionTest() { Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 8443)); this.httpClient = new HttpClient(); // this.httpClient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials("admin", "admin"); this.httpClient.getState().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), defaultcreds); PostMethod method = new PostMethod("https://localhost:8443/engine"); method.addParameter(new NameValuePair("action", "rescan")); try {//from w w w. j a v a 2 s. c o m int status = this.httpClient.executeMethod(method); Header redirectLocation = method.getResponseHeader("location"); String loc = redirectLocation.getValue(); GetMethod getmethod = new GetMethod("https://localhost:8443/engine"); status = this.httpClient.executeMethod(getmethod); System.out.println(status); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { method.releaseConnection(); } }