List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody
public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException
From source file:com.panet.imeta.trans.steps.httppost.HTTPPOST.java
private Object[] callHTTPPOST(Object[] rowData) throws KettleException { // get dynamic url ? if (meta.isUrlInField()) data.realUrl = data.inputRowMeta.getString(rowData, data.indexOfUrlField); try {//from w ww .java2 s . c o m if (log.isDetailed()) logDetailed(Messages.getString("HTTPPOST.Log.ConnectingToURL", data.realUrl)); // Prepare HTTP POST // HttpClient HTTPPOSTclient = new HttpClient(); PostMethod post = new PostMethod(data.realUrl); //post.setFollowRedirects(false); // Specify content type and encoding // If content encoding is not explicitly specified // ISO-8859-1 is assumed if (Const.isEmpty(data.realEncoding)) post.setRequestHeader("Content-type", "text/xml"); else post.setRequestHeader("Content-type", "text/xml; " + data.realEncoding); // BODY PARAMETERS if (data.useBodyParameters) { // set body parameters that we want to send for (int i = 0; i < data.body_parameters_nrs.length; i++) { data.bodyParameters[i] .setValue(data.inputRowMeta.getString(rowData, data.body_parameters_nrs[i])); } post.setRequestBody(data.bodyParameters); } // QUERY PARAMETERS if (data.useQueryParameters) { for (int i = 0; i < data.query_parameters_nrs.length; i++) { data.queryParameters[i] .setValue(data.inputRowMeta.getString(rowData, data.query_parameters_nrs[i])); } post.setQueryString(data.queryParameters); } // Set request entity? if (data.indexOfRequestEntity >= 0) { String tmp = data.inputRowMeta.getString(rowData, data.indexOfRequestEntity); // Request content will be retrieved directly // from the input stream // Per default, the request content needs to be buffered // in order to determine its length. // Request body buffering can be avoided when // content length is explicitly specified if (meta.isPostAFile()) { File input = new File(tmp); post.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length())); } else { post.setRequestEntity( new InputStreamRequestEntity(new ByteArrayInputStream(tmp.getBytes()), tmp.length())); } } // Execute request // InputStream inputStream = null; try { // Execute the POST method int statusCode = HTTPPOSTclient.executeMethod(post); // Display status code if (log.isDebug()) log.logDebug(toString(), Messages.getString("HTTPPOST.Log.ResponseCode", "" + statusCode)); String body = null; if (statusCode != -1) { // the response inputStream = post.getResponseBodyAsStream(); StringBuffer bodyBuffer = new StringBuffer(); int c; while ((c = inputStream.read()) != -1) bodyBuffer.append((char) c); inputStream.close(); // Display response body = bodyBuffer.toString(); if (log.isDebug()) log.logDebug(toString(), Messages.getString("HTTPPOST.Log.ResponseBody", body)); } //return new Value(meta.getFieldName(), body); return RowDataUtil.addValueData(rowData, data.inputRowMeta.size(), body); } finally { if (inputStream != null) inputStream.close(); // Release current connection to the connection pool once you are done post.releaseConnection(); } } catch (Exception e) { throw new KettleException(Messages.getString("HTTPPOST.Error.CanNotReadURL", data.realUrl), e); } }
From source file:com.duroty.controller.actions.GoogieSpellAction.java
protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionMessages errors = new ActionMessages(); PostMethod post = null; try {/*from www . ja v a2s .c o m*/ Enumeration enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); String value = (String) request.getParameter(name); DLog.log(DLog.WARN, this.getClass(), name + " >> " + value); } String text = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><spellrequest textalreadyclipped=\"0\" ignoredups=\"0\" ignoredigits=\"1\" ignoreallcaps=\"1\"><text>" + request.getParameter("check") + "</text></spellrequest>"; String lang = request.getParameter("lang"); String id = request.getParameter("id"); String cmd = request.getParameter("cmd"); String url = "https://" + googleUrl + "/tbproxy/spell?lang=" + lang + "&hl=" + lang; post = new PostMethod(url); post.setRequestBody(text); post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1"); HttpClient client = new HttpClient(); int result = client.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response System.out.println("Response body: "); String resp = post.getResponseBodyAsString(); System.out.println(resp); String goodieSpell = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"; Vector matches = getMatches(resp); if (matches.size() <= 0) { goodieSpell = goodieSpell + "<res id=\"" + id + "\" cmd=\"" + cmd + "\" />"; } else { goodieSpell = goodieSpell + "<res id=\"" + id + "\" cmd=\"" + cmd + "\">"; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < matches.size(); i++) { if (buffer.length() > 0) { buffer.append("+"); } String aux = (String) matches.get(i); aux = aux.substring(aux.indexOf(">") + 1, aux.length()); aux = aux.substring(0, aux.indexOf("<")); aux = aux.trim().replaceAll("\\s+", "\\+"); buffer.append(aux); } goodieSpell = goodieSpell + buffer.toString() + "</res>"; } request.setAttribute("googieSpell", goodieSpell); } catch (Exception ex) { String errorMessage = ExceptionUtilities.parseMessage(ex); if (errorMessage == null) { errorMessage = "NullPointerException"; } errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage)); request.setAttribute("exception", errorMessage); doTrace(request, DLog.ERROR, getClass(), errorMessage); } finally { try { post.releaseConnection(); } catch (Exception e) { } } if (errors.isEmpty()) { doTrace(request, DLog.INFO, getClass(), "OK"); return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD); } else { saveErrors(request, errors); return mapping.findForward(Constants.ACTION_FAIL_FORWARD); } }
From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java
/** * Creates a mandate./* www.j a va2 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); } }
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String obtainAccessTokenResponse(String grantType, String authCode, String clientId, String clientSecret, String uri) {//from www. j a v a2 s . co m PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_ENDPOINT); String response = null; try { NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, grantType), new NameValuePair(CODE_PARAM, authCode), new NameValuePair(REDIRECT_URI_PARAM, uri), new NameValuePair(CLIENT_ID_PARAM, clientId), new NameValuePair(CLIENT_SECRET_PARAM, clientSecret) }; post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); post.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(clientId, clientSecret)); post.setRequestBody(requestBody); response = readResponse(post); log.info(response); } catch (IOException e) { log.error("cannot obtain access token response", e); } return response; }
From source file:at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient.java
/** * Gets a identity link./*w ww . j av a2s.co m*/ * * @param reqElem the request. * @return a SZR-gateway response containing the result * @throws SZRGWException when an error occurs creating the mandate. */ public CreateIdentityLinkResponse createIdentityLinkResponse(Element reqElem) throws SZRGWClientException { try { if (address == null) { throw new NullPointerException("Address (SZR-gateway ServiceURL) must not be null."); } HttpClient client = new HttpClient(); 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); CreateIdentityLinkResponse response = new CreateIdentityLinkResponse(); bos = new ByteArrayOutputStream(); doc = ParepUtils.readDocFromIs(method.getResponseBodyAsStream()); //ParepUtils.saveElementToFile(doc.getDocumentElement(), new File("c:/temp/szrResponse.xml")); NodeList list = doc.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "ErrorResponse"); if (list.getLength() > 0) { // set error response list = doc.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "Info"); String error = DOMUtils.getText(list.item(0)); response.setError(error); } else { // set assertion DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document newdoc = builder.newDocument(); Element nameSpaceNode = newdoc.createElement("NameSpaceNode"); nameSpaceNode.setAttribute("xmlns:" + Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); nameSpaceNode.setAttribute("xmlns:" + Constants.SAML_PREFIX, Constants.SAML_NS_URI); Element samlAssertion = (Element) XPathAPI.selectSingleNode(doc, "//saml:Assertion[1]", nameSpaceNode); if (samlAssertion == null) throw new SZRGWClientException("Could not found a saml:Assertion element in response."); else response.setAssertion(samlAssertion); } return response; } catch (Exception e) { throw new SZRGWClientException(e); } }
From source file:com.snaker.DownloadManager.java
private Runnable createRunnable(final Downloader d) { final Task task = d.getTask(); return new Runnable() { @Override//from ww w . j a v a 2 s .c om public void run() { logger.info("start download:" + d.getUrl()); HttpClient client = clients.get(task.getId()); DownloadHandler handler = d.getHandler(); HttpMethodBase m = null; d.setStatus(Status.STARTED); d.setStartTime(System.currentTimeMillis()); try { String url = d.getUrl(); if (d.isGet()) { GetMethod get = new GetMethod(url); m = get; } else { final String requestCharset = d.getRequestCharset(); PostMethod post = new PostMethod(url) { public String getRequestCharSet() { if (requestCharset != null) return requestCharset; else return super.getRequestCharSet(); } public boolean getFollowRedirects() { return d.isFollowRedirects(); } }; if (requestCharset != null) { post.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=" + requestCharset); } DownloadParams parms = d.getParms(); if (parms != null) post.setRequestBody(parms.toNVP()); m = post; } { // set the headers m.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:8.0.1) Gecko/20100101 Firefox/8.0.1"); m.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); m.setRequestHeader("Accept-Language", "en-us,zh-cn;q=0.5"); m.setRequestHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); m.setRequestHeader("Referer", url); } client.executeMethod(m); //check status int sc = m.getStatusCode(); d.setStatusCode(sc); if (isBadStatusCode(sc)) { logger.error("download failed,url:" + d.getUrl() + ",Status Code:" + sc); d.setStatus(Status.FAILED); d.setDescription(m.getStatusText()); return; } else if (sc == 404 || sc == 410) { d.setStatus(Status.FINISHED); d.setDescription("NOT FOUND"); return; } long size = m.getResponseContentLength(); d.setFileSize(size); // get File Name if (d.getFileName() == null) { Header h = m.getResponseHeader("Content-Disposition"); String fileName = null; if (h != null) { String f = h.getValue(); int tag = f.indexOf("filename="); if (tag != -1 && tag != f.length() - 1) fileName = f.substring(tag + 1); } if (fileName == null || fileName.length() == 0) { int tag1 = url.lastIndexOf("/"); int tag2 = url.lastIndexOf("?"); if (tag1 != -1 && tag1 != url.length() - 1) { if (tag2 > tag1) { fileName = url.substring(tag1 + 1, tag2); } else { fileName = url.substring(tag1 + 1); } } } d.setFileName(fileName); } // set the all headers Header[] headers = m.getResponseHeaders(); if (headers != null) { for (Header header : headers) { d.addResponseHeader(header.getName(), header.getValue()); } } d.setStatus(Status.RUNNING); // recv the body if (handler == null) { byte[] content = m.getResponseBody(); int len = content.length; d.setFileSize(len); d.setReceived(len); d.setResponseCharset(m.getResponseCharSet()); d.setResponseBody(content); } else { InputStream is = m.getResponseBodyAsStream(); handler.start(d); byte[] buffer = new byte[102400]; long count = 0; while (true) { int r = is.read(buffer); if (r > 0) { count += r; d.setReceived(count); handler.handle(buffer, r); } else { break; } } is.close(); } d.setStatus(Status.FINISHED); } catch (Exception e) { logger.error("download failed,url:" + d.getUrl(), e); d.setStatus(Status.FAILED); d.setDescription(e.getMessage()); } finally { m.releaseConnection(); if (handler != null) { handler.stop(); } downloadings.remove(d); d.setEndTime(System.currentTimeMillis()); while (downloaded.size() >= maxDownloadedCount) { downloaded.poll(); } downloaded.offer(d); task.downloadFininshed(d); } } }; }
From source file:edu.ku.brc.af.core.SpecialMsgNotifier.java
/** * @param item/* ww w . jav a2 s . c om*/ * @throws Exception */ protected String send(final String url, final String id) throws Exception { // check the website for the info about the latest version HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter("http.useragent", getClass().getName()); //$NON-NLS-1$ httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000); PostMethod postMethod = new PostMethod(url); Vector<NameValuePair> postParams = new Vector<NameValuePair>(); postParams.add(new NameValuePair("id", id)); //$NON-NLS-1$ String resAppVersion = UIRegistry.getAppVersion(); resAppVersion = StringUtils.isEmpty(resAppVersion) ? "Unknown" : resAppVersion; // get the OS name and version postParams.add(new NameValuePair("os_name", System.getProperty("os.name"))); //$NON-NLS-1$ postParams.add(new NameValuePair("os_version", System.getProperty("os.version"))); //$NON-NLS-1$ postParams.add(new NameValuePair("java_version", System.getProperty("java.version"))); //$NON-NLS-1$ postParams.add(new NameValuePair("java_vendor", System.getProperty("java.vendor"))); //$NON-NLS-1$ postParams.add(new NameValuePair("app_version", UIRegistry.getAppVersion())); //$NON-NLS-1$ // create an array from the params NameValuePair[] paramArray = new NameValuePair[postParams.size()]; for (int i = 0; i < paramArray.length; ++i) { paramArray[i] = postParams.get(i); } postMethod.setRequestBody(paramArray); // connect to the server try { httpClient.executeMethod(postMethod); int status = postMethod.getStatusCode(); if (status == 200) { // get the server response String responseString = postMethod.getResponseBodyAsString(); if (StringUtils.isNotEmpty(responseString)) { return responseString; } } } catch (java.net.UnknownHostException ex) { log.debug("Couldn't reach host."); } catch (Exception e) { e.printStackTrace(); // die silently } return null; }
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String obtainPasswordCredentialsAccessTokenResponse(String currentClientId, String currentClientSecret, String username, String password, String scope, boolean addAuthHeader) { PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_ENDPOINT); String response = null;/*from w w w . j av a2 s . c o m*/ try { post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); if (addAuthHeader) { post.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(currentClientId, currentClientSecret)); NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, GRANT_TYPE_PASSWORD), new NameValuePair("username", username), new NameValuePair("password", password), new NameValuePair(SCOPE_PARAM, scope) }; post.setRequestBody(requestBody); } else { NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, GRANT_TYPE_PASSWORD), new NameValuePair("username", username), new NameValuePair("password", password), new NameValuePair(SCOPE_PARAM, scope), new NameValuePair(CLIENT_ID_PARAM, currentClientId), new NameValuePair(CLIENT_SECRET_PARAM, currentClientSecret) }; post.setRequestBody(requestBody); } response = readResponse(post); log.info(response); } catch (IOException e) { log.error("cannot obtain password acces token response", e); } return response; }
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String obtainAccessToken(String grantType, String authCode, String clientId, String clientSecret, String uri) {//w w w.jav a2 s .co m PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_ENDPOINT); String accessToken = null; String response = null; try { NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, grantType), new NameValuePair(CODE_PARAM, authCode), new NameValuePair(REDIRECT_URI_PARAM, uri), new NameValuePair(CLIENT_ID_PARAM, clientId), new NameValuePair(CLIENT_SECRET_PARAM, clientSecret) }; post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); post.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(clientId, clientSecret)); post.setRequestBody(requestBody); response = readResponse(post); log.info(response); if (response != null) { accessToken = extractAccessToken(response); } } catch (IOException e) { log.error("cannot obtain access token", e); } return accessToken; }
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String obtainAccessTokenByRefreshTokenResponse(String grantType, String refreshToken, String clientId, String clientSecret, String scope) { PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_ENDPOINT); String response = null;//from w w w . ja v a2s . c o m try { post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); //post.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(clientId, clientSecret)); if (scope != null) { NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, grantType), new NameValuePair(REFRESH_TOKEN_PARAM, refreshToken), new NameValuePair(SCOPE_PARAM, scope), new NameValuePair(CLIENT_ID_PARAM, clientId), new NameValuePair(CLIENT_SECRET_PARAM, clientSecret) }; post.setRequestBody(requestBody); } else { NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, grantType), new NameValuePair(REFRESH_TOKEN_PARAM, refreshToken), new NameValuePair(CLIENT_ID_PARAM, clientId), new NameValuePair(CLIENT_SECRET_PARAM, clientSecret) }; post.setRequestBody(requestBody); } response = readResponse(post); log.info(response); } catch (IOException e) { log.error("cannot obtain access token by refresh token response", e); } return response; }