List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod
public PostMethod(String paramString)
From source file:com.sap.netweaver.porta.core.nw7.FileUploaderImpl.java
public String[] upload(File[] archives) throws CoreException { // check if there are any credentials already set if (client == null) { // trigger the mechanism for requesting user for credentials throw new NotAuthorizedException(FAULT_UNAUTHORIZED.getFaultReason()); }//from w w w .j a v a2 s. c om PostMethod method = null; try { Part[] parts = new Part[archives.length]; for (int i = 0; i < archives.length; i++) { parts[i] = new FilePart(archives[i].getName(), archives[i]); } method = new PostMethod(url); method.setDoAuthentication(true); method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { throw new NotAuthorizedException(FAULT_INVALID_CREDENTIALS.getFaultReason()); } else if (statusCode == HttpStatus.SC_FORBIDDEN) { throw new NotAuthorizedException(FAULT_PERMISSION_DENIED.getFaultReason()); } else if (statusCode == HttpStatus.SC_NOT_FOUND) { throw new NoWSGateException(null, url); } else if (statusCode != HttpStatus.SC_OK) { throw new CoreException(method.getStatusText()); } InputStream responseStream = method.getResponseBodyAsStream(); BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseStream)); String line; List<String> paths = new ArrayList<String>(); while ((line = responseReader.readLine()) != null) { paths.add(line); } responseReader.close(); responseStream.close(); return paths.toArray(new String[] {}); } catch (HttpException e) { throw new CoreException(e); } catch (IOException e) { throw new CoreException(e); } finally { if (method != null) { method.releaseConnection(); } } }
From source file:io.hawt.web.JBossPostApp.java
@Test public void testPostWithAuthorizationHeader() throws Exception { System.out.println("Using URL: " + url + " user: " + userName + " password: " + password); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); String userPwd = userName + ":" + password; String hash = new Base64().encodeAsString(userPwd.getBytes()); method.setRequestHeader("Authorization", "Basic " + hash); System.out.println("headers " + Arrays.asList(method.getRequestHeaders())); method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8")); int result = client.executeMethod(method); System.out.println("Status: " + result); String response = method.getResponseBodyAsString(); System.out.println(response); }
From source file:com.epam.wilma.gepard.testclient.MultiStubHttpPostRequestSender.java
/** * Sends a new HTTP request to a server through a proxy. Also logs request and response with gepard framework. * * @param tc the running test case * @param requestParameters a set of parameters that will set the content of the request * and specify the proxy it should go through * @return with Response Holder class./* w w w.ja v a2s. c om*/ * @throws IOException in case error occurs * @throws ParserConfigurationException in case error occurs * @throws SAXException in case error occurs */ public ResponseHolder callWilmaTestServer(final WilmaTestCase tc, final MultiStubRequestParameters requestParameters) throws IOException, ParserConfigurationException, SAXException { String responseCode; ResponseHolder responseMessage; HttpClient httpClient = new HttpClient(); PostMethod httpPost = new PostMethod(requestParameters.getTestServerUrl()); if (requestParameters.isUseProxy()) { httpClient.getHostConfiguration().setProxy(requestParameters.getWilmaHost(), requestParameters.getWilmaPort()); } createRequest(requestParameters, httpPost); httpClient.getHttpConnectionManager().getParams().setSendBufferSize(Integer .valueOf(tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.sendbuffer"))); httpClient.getHttpConnectionManager().getParams().setReceiveBufferSize(Integer .valueOf(tc.getTestClassExecutionData().getEnvironment().getProperty("http.socket.receivebuffer"))); int statusCode; statusCode = httpClient.executeMethod(httpPost); responseCode = "status code: " + statusCode + "\n"; responseMessage = createResponse(httpPost); responseMessage.setResponseCode(responseCode); tc.setActualResponseCode(statusCode); Header contentTypeHeader = httpPost.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { tc.setActualResponseContentType(contentTypeHeader.getValue()); } Header sequenceHeader = httpPost.getResponseHeader("Wilma-Sequence"); if (sequenceHeader != null) { tc.setActualDialogDescriptor(sequenceHeader.getValue()); } return responseMessage; }
From source file:de.juwimm.cms.http.AuthenticationStreamSupportingHttpInvokerRequestExecutor.java
protected PostMethod createPostMethodForStreaming(final HttpInvokerClientConfiguration config) throws IOException { HttpClientWrapper.getInstance().setHostConfiguration(super.getHttpClient(), new URL(config.getServiceUrl())); final PostMethod postMethod = new PostMethod(config.getServiceUrl()); postMethod.setRequestHeader(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_SERIALIZED_OBJECT_WITH_STREAM); //Solution for TIZZIT-282 //postMethod.setContentChunked(true); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if ((auth != null) && (auth.getName() != null) && (auth.getCredentials() != null)) { postMethod.setDoAuthentication(true); String base64 = auth.getName() + ":" + auth.getCredentials().toString(); postMethod.addRequestHeader("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes()))); if (log.isDebugEnabled()) { // log.debug("HttpInvocation now presenting via BASIC // authentication SecurityContextHolder-derived: " + // auth.toString()); log.debug(/*from w w w . j a v a 2 s . com*/ "HttpInvocation now presenting via BASIC authentication SecurityContextHolder-derived. User: " + auth.getName()); } } else { if (log.isDebugEnabled()) { log.debug("Unable to set BASIC authentication header as SecurityContext did not provide " + "valid Authentication: " + auth); } } return postMethod; }
From source file:demo.jaxrs.client.Client.java
public void addCustomerInfo(String name, String password) throws Exception { System.out.println("HTTP POST to add customer info, user : " + name + ", password : " + password); PostMethod post = new PostMethod("http://localhost:9002/customerservice/customers"); setMethodHeaders(post, name, password); RequestEntity entity = new InputStreamRequestEntity( this.getClass().getClassLoader().getResourceAsStream("add_customer.xml")); post.setRequestEntity(entity);/*from w ww .ja va 2 s. c om*/ handleHttpMethod(post); }
From source file:com.owncloud.android.operations.CommentFileOperation.java
/** * Performs the operation.// ww w . j av a 2 s.com * * @param client Client object to communicate with the remote ownCloud server. */ @Override protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result; try { String url = client.getNewWebdavUri() + "/comments/files/" + fileId; PostMethod postMethod = new PostMethod(url); postMethod.addRequestHeader("Content-type", "application/json"); Map<String, String> values = new HashMap<>(); values.put(ACTOR_ID, userId); values.put(ACTOR_TYPE, ACTOR_TYPE_VALUE); values.put(VERB, VERB_VALUE); values.put(MESSAGE, message); String json = new GsonBuilder().create().toJson(values, Map.class); postMethod.setRequestEntity(new StringRequestEntity(json)); int status = client.executeMethod(postMethod, POST_READ_TIMEOUT, POST_CONNECTION_TIMEOUT); result = new RemoteOperationResult(isSuccess(status), postMethod); client.exhaustResponse(postMethod.getResponseBodyAsStream()); } catch (IOException e) { result = new RemoteOperationResult(e); Log.e(TAG, "Post comment to file with id " + fileId + " failed: " + result.getLogMessage(), e); } return result; }
From source file:com.glaf.core.util.http.CommonsHttpClientUtils.java
/** * ??POST//from w w w . j a v a2 s. c om * * @param url * ?? * @param encoding * * @param dataMap * ? * * @return */ public static String doPost(String url, String encoding, Map<String, String> dataMap) { PostMethod method = null; String content = null; try { method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + encoding); if (dataMap != null && !dataMap.isEmpty()) { NameValuePair[] nameValues = new NameValuePair[dataMap.size()]; int i = 0; for (Map.Entry<String, String> entry : dataMap.entrySet()) { String name = entry.getKey().toString(); String value = entry.getValue(); nameValues[i] = new NameValuePair(name, value); i++; } method.setRequestBody(nameValues); } HttpClient client = new HttpClient(); int status = client.executeMethod(method); if (status == HttpStatus.SC_OK) { content = method.getResponseBodyAsString(); } } catch (IOException ex) { throw new RuntimeException(ex); } finally { if (method != null) { method.releaseConnection(); method = null; } } return content; }
From source file:br.org.acessobrasil.silvinha.util.versoes.VerificadorDeVersoes.java
public boolean verificarVersao(Versao versaoCliente) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); NameValuePair param = new NameValuePair("param", "check"); method.setRequestBody(new NameValuePair[] { param }); DefaultHttpMethodRetryHandler retryHandler = null; retryHandler = new DefaultHttpMethodRetryHandler(0, false); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler); try {/*www . j a v a 2 s .c o m*/ //System.out.println(Silvinha.VERIFICADOR_VERSOES+client.getState().toString()); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { log.error("Method failed: " + method.getStatusLine()); } // Read the response body. byte[] responseBody = method.getResponseBody(); String rb = new String(responseBody).trim(); Versao versaoServidor = null; try { versaoServidor = new Versao(rb); } catch (NumberFormatException nfe) { return false; } if (versaoCliente.compareTo(versaoServidor) < 0) { AtualizadorDeVersoes av = new AtualizadorDeVersoes(url); return av.confirmarAtualizacao(); } else { return false; } } catch (HttpException he) { log.error("Fatal protocol violation: " + he.getMessage(), he); return false; } catch (IOException ioe) { log.error("Fatal transport error: " + ioe.getMessage(), ioe); return false; } catch (Exception e) { return false; } finally { //Release the connection. method.releaseConnection(); } }
From source file:net.neurowork.cenatic.centraldir.workers.XMLPusher.java
private void pushOrganization(RestUrlManager restUrl, String token) { HttpClient httpclient = XMLRestWorker.getHttpClient(); PostMethod post = new PostMethod(restUrl.getPushOrganizationUrl()); NameValuePair tokenParam = new NameValuePair("token", token); NameValuePair[] params = new NameValuePair[] { tokenParam }; post.addRequestHeader("Accept", "application/xml"); post.setQueryString(params);//from w ww.j a va2s . c om String content = XmlPushCreator.getInstance().getPushXml(organizacion); try { RequestEntity entity = new StringRequestEntity(content, PostMethod.FORM_URL_ENCODED_CONTENT_TYPE, null); post.setRequestEntity(entity); int result = httpclient.executeMethod(post); logger.info("Response status code: " + result); logger.info("Response body: "); logger.info(post.getResponseBodyAsString()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); } catch (HttpException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } finally { post.releaseConnection(); } }
From source file:edu.harvard.iq.dvn.core.web.dvnremote.ICPSRauth.java
public String obtainAuthCookie(String username, String password, String fileDownloadUrl) { PostMethod loginPostMethod = null;/*from w w w. j av a 2 s. c o m*/ if (username == null || password == null) { return null; } int status = 0; String icpsrAuthCookie = null; try { dbgLog.fine("entering ICPSR auth;"); HttpClient httpclient = getClient(); loginPostMethod = new PostMethod(icpsrLoginUrl); Part[] parts = { new StringPart("email", username), new StringPart("password", password), new StringPart("path", "ICPSR"), new StringPart("request_uri", fileDownloadUrl) }; loginPostMethod.setRequestEntity(new MultipartRequestEntity(parts, loginPostMethod.getParams())); status = httpclient.executeMethod(loginPostMethod); dbgLog.fine("executed POST method; status=" + status); if (status != 200) { loginPostMethod.releaseConnection(); return null; } String regexpTicketCookie = "(Ticket=[^;]*)"; Pattern patternTicketCookie = Pattern.compile(regexpTicketCookie); for (int i = 0; i < loginPostMethod.getResponseHeaders().length; i++) { String headerName = loginPostMethod.getResponseHeaders()[i].getName(); if (headerName.equalsIgnoreCase("set-cookie")) { String cookieHeader = loginPostMethod.getResponseHeaders()[i].getValue(); Matcher cookieMatcher = patternTicketCookie.matcher(cookieHeader); if (cookieMatcher.find()) { icpsrAuthCookie = cookieMatcher.group(1); dbgLog.fine("detected ICPSR ticket cookie: " + cookieHeader); } } } loginPostMethod.releaseConnection(); return icpsrAuthCookie; } catch (IOException ex) { dbgLog.info("ICPSR auth: caught IO exception."); ex.printStackTrace(); if (loginPostMethod != null) { loginPostMethod.releaseConnection(); } return null; } }