List of usage examples for org.apache.commons.httpclient.methods PostMethod PostMethod
public PostMethod(String paramString)
From source file:eu.eco2clouds.api.bonfire.client.rest.RestClient.java
/** * Performs a POST method against the API * @param url -> This URL is going to be converted to API_URL:BONFIRE_PORT/url * @param payload message sent in the post method * @param type specifies the content type of the request * @return Response object encapsulation all the HTTP information, it returns <code>null</code> if there was an error. *//* www . j a va 2 s.com*/ public static Response executePostMethod(String url, String username, String password, String payload, String type) { Response response = null; try { PostMethod post = new PostMethod(url); // We define the request entity RequestEntity requestEntity = new StringRequestEntity(payload, type, null); post.setRequestEntity(requestEntity); response = executeMethod(post, BONFIRE_XML, username, password, url); } catch (UnsupportedEncodingException exception) { System.out.println("THE PAYLOAD ENCODING IS NOT SUPPORTED"); System.out.println("ERROR: " + exception.getMessage()); System.out.println("ERROR: " + exception.getStackTrace()); } return response; }
From source file:com.boyuanitsm.pay.alipay.util.httpClient.HttpProtocolHandler.java
/** * Http/*from w w w .j a v a2 s. com*/ * * @param request ? * @param strParaFileName ??? * @param strFilePath * @return * @throws HttpException, IOException */ public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath) throws HttpException, IOException { HttpClient httpclient = new HttpClient(connectionManager); // int connectionTimeout = defaultConnectionTimeout; if (request.getConnectionTimeout() > 0) { connectionTimeout = request.getConnectionTimeout(); } httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); // int soTimeout = defaultSoTimeout; if (request.getTimeout() > 0) { soTimeout = request.getTimeout(); } httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout); // ConnectionManagerconnection httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout); String charset = request.getCharset(); charset = charset == null ? DEFAULT_CHARSET : charset; HttpMethod method = null; //get?? if (request.getMethod().equals(HttpRequest.METHOD_GET)) { method = new GetMethod(request.getUrl()); method.getParams().setCredentialCharset(charset); // parseNotifyConfig??GETrequestQueryString method.setQueryString(request.getQueryString()); } else if (strParaFileName.equals("") && strFilePath.equals("")) { //post?? method = new PostMethod(request.getUrl()); ((PostMethod) method).addParameters(request.getParameters()); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset); } else { //post? method = new PostMethod(request.getUrl()); List<Part> parts = new ArrayList<Part>(); for (int i = 0; i < request.getParameters().length; i++) { parts.add(new StringPart(request.getParameters()[i].getName(), request.getParameters()[i].getValue(), charset)); } //?strParaFileName??? parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath)))); // ((PostMethod) method).setRequestEntity( new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams())); } // Http HeaderUser-Agent method.addRequestHeader("User-Agent", "Mozilla/4.0"); HttpResponse response = new HttpResponse(); try { httpclient.executeMethod(method); if (request.getResultType().equals(HttpResultType.STRING)) { response.setStringResult(method.getResponseBodyAsString()); } else if (request.getResultType().equals(HttpResultType.BYTES)) { response.setByteResult(method.getResponseBody()); } response.setResponseHeaders(method.getResponseHeaders()); } catch (UnknownHostException ex) { return null; } catch (IOException ex) { return null; } catch (Exception ex) { return null; } finally { method.releaseConnection(); } return response; }
From source file:com.pureinfo.force.net.impl.HttpUtilImplTest.java
public void testResponseCharset() throws Exception { final String sUrl = "http://srm.pureinfo.com.cn/srm/Login.do"; //final String sUrl = // "http://199.155.122.100:9521/srm-center/data-sync.do"; HttpClient client = new HttpClient(); PostMethod method = new PostMethod(sUrl); method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); try {/*from www. jav a 2 s . c om*/ client.executeMethod(method); System.out.println("charset=" + method.getResponseCharSet()); String sContent = method.getResponseBodyAsString(); System.out.println("content=" + sContent); } finally { method.releaseConnection(); } }
From source file:com.dtolabs.client.utils.HttpClientChannel.java
/** * Create new HttpMethod objects for the requestUrl, and set any request headers specified previously *///ww w.j a va 2s . c o m private HttpMethod initMethod() { if ("GET".equalsIgnoreCase(getMethodType())) { httpMethod = new GetMethod(requestUrl); } else if ("POST".equalsIgnoreCase(getMethodType())) { httpMethod = new PostMethod(requestUrl); } else if ("PUT".equalsIgnoreCase(getMethodType())) { httpMethod = new PutMethod(requestUrl); } else if ("DELETE".equalsIgnoreCase(getMethodType())) { httpMethod = new DeleteMethod(requestUrl); } else { throw new IllegalArgumentException("Unknown method type: " + getMethodType()); } if (reqHeaders.size() > 0) { for (Iterator i = reqHeaders.keySet().iterator(); i.hasNext();) { String s = (String) i.next(); String v = (String) reqHeaders.get(s); httpMethod.setRequestHeader(s, v); } } return httpMethod; }
From source file:net.mojodna.searchable.solr.SolrIndexer.java
/** * Serialize the Document and hand it to Solr. *///from w w w . j a v a 2 s .co m @Override protected void save(final Document doc) throws IndexingException { final Element add = new Element("add"); add.addContent(DocumentConverter.convert(doc)); // now do something with the add block try { final XMLOutputter out = new XMLOutputter(Format.getPrettyFormat()); final String addString = out.outputString(add); final PostMethod post = new PostMethod(solrPath); post.setRequestEntity(new StringRequestEntity(addString, "text/xml", "UTF-8")); log.debug("Adding:\n" + addString); getHttpClient().executeMethod(post); if (!isBatchMode()) { commit(); } } catch (final IOException e) { throw new IndexingException(e); } }
From source file:gr.upatras.ece.nam.fci.panlab.PanlabGWClient.java
/** * It makes a POST towards the gateway/* w w w . j a v a 2 s. c om*/ * @author ctranoris * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) { boolean status = false; System.out.println("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = panlabGWAddress + "/" + ptm + "/" + resourceInstance; System.out.println("Request: " + url); // Create a method instance. PostMethod post = new PostMethod(url); post.setRequestHeader("User-Agent", userAgent); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); //HttpMethodParams. RequestEntity requestEntity = null; try { requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } post.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = post.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); System.out.println("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // System.out.println("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); status = true; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); return false; } finally { // Release the connection. post.releaseConnection(); } return status; }
From source file:net.jadler.JadlerMockingIntegrationTest.java
@Test public void havingISOBody() throws Exception { final PostMethod method = new PostMethod("http://localhost:" + port()); method.setRequestEntity(//from www .jav a2 s.c o m new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", ISO_8859_2_CHARSET.name())); client.executeMethod(method); verifyThatRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS) .havingRawBodyEqualTo(ISO_8859_2_REPRESENTATION).receivedOnce(); }
From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.services.SettingsLoaderImpl.java
public void revertToPreviousConfiguration(RemoteSettings remoteSettings) throws SettingsLoaderException { try {//from ww w .j a v a 2s .c om logger.debug("Attempting to revert to previous configuration for '" + remoteSettings.getSettings().getEid() + "'"); PostMethod method = new PostMethod(remoteSettings.getBasePath() + "/hqu/tomcatserverconfig/tomcatserverconfig/revertToPreviousConfiguration.hqu"); configureMethod(method, remoteSettings.getSettings().getEid(), remoteSettings.getSessionId(), remoteSettings.getCsrfNonce()); httpClient.executeMethod(method); if (method.getStatusCode() >= 300 && method.getStatusCode() < 400) { logger.info("Unable to revert to previous configuration for '" + remoteSettings.getSettings().getEid() + "', HQ session expired"); throw new SettingsLoaderException(SESSION_EXPIRED_MESSAGE); } else if (method.getStatusCode() >= 400) { logger.warn( "Unable to revert to previous configuration for '" + remoteSettings.getSettings().getEid() + "', " + method.getStatusCode() + " " + method.getStatusText()); throw new SettingsLoaderException(method.getStatusText()); } remoteSettings.setCsrfNonce(method.getResponseBodyAsString()); logger.info("Reverted to previous configuration for '" + remoteSettings.getSettings().getEid() + "'"); } catch (SSLHandshakeException e) { logger.error("Server SSL certificate is untrusted: " + e.getMessage(), e); throw new SettingsLoaderException( "Unable to revert to previous configuration because the server is using an untrusted SSL certificate. " + "Please check the documentation for more information.", e); } catch (IOException e) { logger.error("Unable to revert to previous configuration for '" + remoteSettings.getSettings().getEid() + "': " + e.getMessage(), e); throw new SettingsLoaderException( "Reverting to previous configuration failed because of a server error, please check the logs for more details", e); } }
From source file:ke.go.moh.oec.adt.Daemon.java
private static boolean sendMessage(String url, String filename) { int returnStatus = HttpStatus.SC_CREATED; HttpClient httpclient = new HttpClient(); HttpConnectionManager connectionManager = httpclient.getHttpConnectionManager(); connectionManager.getParams().setSoTimeout(120000); PostMethod httpPost = new PostMethod(url); RequestEntity requestEntity;// w ww. ja v a2 s . c o m try { FileInputStream message = new FileInputStream(filename); Base64InputStream message64 = new Base64InputStream(message, true, -1, null); requestEntity = new InputStreamRequestEntity(message64, "application/octet-stream"); } catch (FileNotFoundException e) { Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "File not found.", e); return false; } httpPost.setRequestEntity(requestEntity); try { httpclient.executeMethod(httpPost); returnStatus = httpPost.getStatusCode(); } catch (SocketTimeoutException e) { returnStatus = HttpStatus.SC_REQUEST_TIMEOUT; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Request timed out. Not retrying.", e); } catch (HttpException e) { returnStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "HTTP exception. Not retrying.", e); } catch (ConnectException e) { returnStatus = HttpStatus.SC_SERVICE_UNAVAILABLE; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Service unavailable. Not retrying.", e); } catch (UnknownHostException e) { returnStatus = HttpStatus.SC_NOT_FOUND; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "Not found. Not retrying.", e); } catch (IOException e) { returnStatus = HttpStatus.SC_GATEWAY_TIMEOUT; Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, "IO exception. Not retrying.", e); } finally { httpPost.releaseConnection(); } return returnStatus == HttpStatus.SC_OK; }
From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java
/** * Creates a mandate.//from ww w . j a v a 2 s .c o m * * @param reqElem the request. * @return a SZR-gateway response containing the result * @throws SZRGWException when an error occurs creating the mandate. */ public CreateMandateResponse createMandateResponse(Element reqElem) throws SZRGWClientException { //Logger.info("Connecting to SZR-gateway."); try { if (address == null) { throw new NullPointerException("Address (SZR-gateway ServiceURL) must not be null."); } HttpClient client = HttpClientWithProxySupport.getHttpClient(); PostMethod method = new PostMethod(address); method.setRequestHeader("SOAPAction", ""); // ssl settings if (sSLSocketFactory != null) { SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory); Protocol.registerProtocol("https", new Protocol("https", fac, 443)); } // create soap body Element soapBody = getSOAPBody(); Document doc = soapBody.getOwnerDocument(); soapBody.appendChild(doc.importNode(reqElem, true)); Element requestElement = soapBody.getOwnerDocument().getDocumentElement(); //ParepUtils.saveElementToFile(requestElement, new File("c:/temp/szrRequest.xml")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ParepUtils.serializeElementAsDocument(requestElement, bos); method.setRequestBody(new ByteArrayInputStream(bos.toByteArray())); client.executeMethod(method); CreateMandateResponse response = new CreateMandateResponse(); bos = new ByteArrayOutputStream(); doc = ParepUtils.readDocFromIs(method.getResponseBodyAsStream()); //ParepUtils.saveElementToFile(doc.getDocumentElement(), new File("c:/temp/szrResponse.xml")); response.parse(doc.getDocumentElement()); return response; } catch (Exception e) { //e.printStackTrace(); throw new SZRGWClientException(e); } }