List of usage examples for org.apache.commons.httpclient HttpMethod setQueryString
public abstract void setQueryString(NameValuePair[] paramArrayOfNameValuePair);
From source file:org.wingsource.plugin.impl.gadget.bean.Gadget.java
private Response getResponse(String tokenId, String href, Map<String, String> requestParameters) { logger.finest("Fetching content using HttpClient....user-Id: " + tokenId); HttpClient hc = new HttpClient(); hc.getHttpConnectionManager().getParams().setConnectionTimeout(5000); HttpMethod method = new GetMethod(href); method.addRequestHeader("xx-wings-user-id", tokenId); ArrayList<NameValuePair> nvpList = new ArrayList<NameValuePair>(); Set<String> keys = requestParameters.keySet(); for (String key : keys) { String value = requestParameters.get(key); nvpList.add(new NameValuePair(key, value)); }/*from ww w. ja v a 2 s. co m*/ String qs = method.getQueryString(); if (qs != null) { String[] nvPairs = qs.split("&"); for (String nvPair : nvPairs) { String[] mapping = nvPair.split("="); nvpList.add(new NameValuePair(mapping[0], mapping[1])); } } method.setFollowRedirects(true); NameValuePair[] nvps = new NameValuePair[nvpList.size()]; nvps = nvpList.toArray(nvps); method.setQueryString(nvps); byte[] content = null; Header[] headers = null; try { hc.executeMethod(method); content = method.getResponseBody(); headers = method.getResponseHeaders(); } catch (HttpException e) { logger.log(Level.SEVERE, e.getMessage(), e); } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); } return new Response(content, headers); }
From source file:org.wso2.appserver.integration.tests.javaee.jsf.JsfBValTestCase.java
@Test(groups = "wso2.as", description = "test JSF Bean Validation") public void testJsfBVal() throws Exception { String CalculatorEndpoint = webAppURL + "/index.jsf"; //here used Commons http client in order to manage same session throughout HttpMethod getMethod = new GetMethod(CalculatorEndpoint); HttpClient client = new HttpClient(); client.executeMethod(getMethod);//from w ww . j a va 2s . c om String getResponse = getMethod.getResponseBodyAsString(); log.info("getResponse - " + getResponse); //extracting jsf viewState from the get request DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource inputSource = new InputSource(new StringReader(getResponse)); Document document = documentBuilder.parse(inputSource); //Evaluate XPath against Document XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate("//input[3]/@value", document.getDocumentElement(), XPathConstants.NODESET); String viewState = nodes.item(0).getNodeValue(); HttpMethod postMethod = new PostMethod(CalculatorEndpoint); NameValuePair[] nameValuePairs = new NameValuePair[5]; nameValuePairs[0] = new NameValuePair("j_id_4:j_id_8", "88"); nameValuePairs[1] = new NameValuePair("j_id_4:j_id_b", "99"); nameValuePairs[2] = new NameValuePair("j_id_4:j_id_c", "Calculate"); nameValuePairs[3] = new NameValuePair("j_id_4_SUBMIT", "1"); nameValuePairs[4] = new NameValuePair("javax.faces.ViewState", viewState); postMethod.setQueryString(nameValuePairs); client.executeMethod(postMethod); String postResponse = postMethod.getResponseBodyAsString(); log.info("postResponse - " + postResponse); assertTrue(postResponse.contains("187"), "Response doesn't contain expected data"); }
From source file:org.wso2.appserver.integration.tests.javaee.jsf.JsfEjbTestCase.java
@Test(groups = "wso2.as", description = "test JSF Bean Validation") public void testJsfEjb() throws Exception { String CalculatorEndpoint = webAppURL + "/index.jsf"; //here used Commons http client in order to manage same session throughout HttpMethod getMethod = new GetMethod(CalculatorEndpoint); HttpClient client = new HttpClient(); client.executeMethod(getMethod);/*w w w . ja va 2 s.c om*/ String getResponse = getMethod.getResponseBodyAsString(); log.info("getResponse - " + getResponse); //extracting jsf viewState from the get request DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource inputSource = new InputSource(new StringReader(getResponse)); Document document = documentBuilder.parse(inputSource); //Evaluate XPath against Document XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.evaluate("//input[4]/@value", document.getDocumentElement(), XPathConstants.NODESET); String viewState = nodes.item(0).getNodeValue(); HttpMethod postMethod = new PostMethod(CalculatorEndpoint); NameValuePair[] nameValuePairs = new NameValuePair[4]; nameValuePairs[0] = new NameValuePair("j_id_4:j_id_6", "John Doe"); nameValuePairs[1] = new NameValuePair("j_id_4:j_id_7", "Enter"); nameValuePairs[2] = new NameValuePair("j_id_4_SUBMIT", "1"); nameValuePairs[3] = new NameValuePair("javax.faces.ViewState", viewState); postMethod.setQueryString(nameValuePairs); client.executeMethod(postMethod); String postResponse = postMethod.getResponseBodyAsString(); log.info("postResponse - " + postResponse); assertTrue(postResponse.contains("Welcome John Doe"), "Response doesn't contain expected data"); assertTrue(postResponse.contains("Distinct characters in the name: j, o, h, n, d, e"), "Response doesn't contain expected data"); }
From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.PooledHttpClientHostObject.java
/** * Used by jsFunction_executeMethod().//from w w w.ja v a2s .co m * * @param httpClient * @param contentType * @param charset * @param methodName * @param content */ private static void setContent(HttpMethod method, String contentType, String charset, String methodName, Object content) { // content is set, but params has not set // use default content type and encoding when posting if (methodName.equals("POST")) { if (content instanceof String) { try { ((PostMethod) method) .setRequestEntity(new StringRequestEntity((String) content, contentType, charset)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Charset"); } } else { NativeObject element; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); pairs.add(new NameValuePair(eName, eValue)); } else { throw new RuntimeException("Invalid content definition, objects of the content array " + "should consists with strings for both key/value"); } } else { throw new RuntimeException( "Invalid content definition, content array should contain " + "Javascript Objects"); } } ((PostMethod) method).setRequestBody(pairs.toArray(new NameValuePair[pairs.size()])); } } else if (methodName.equals("GET")) { if (content instanceof String) { method.setQueryString((String) content); } else { NativeObject element; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); pairs.add(new NameValuePair(eName, eValue)); } else { throw new RuntimeException("Invalid content definition, objects of the content array " + "should consists with strings for both key/value"); } } else { throw new RuntimeException( "Invalid content definition, content array should contain " + "Javascript Objects"); } } method.setQueryString(pairs.toArray(new NameValuePair[pairs.size()])); } } else if (methodName.equals("PUT")) { // here, the method now is PUT if (content != null) { if (content instanceof String) { try { ((PutMethod) method) .setRequestEntity(new StringRequestEntity((String) content, contentType, charset)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Charset"); } } else { throw new RuntimeException( "Invalid content definition, content should be a string when PUT " + "method is used"); } } } }
From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.PooledHttpClientHostObject.java
/** * Used by jsFunction_executeMethod().//w ww . ja v a2 s .co m * * @param httpClient * @param contentType * @param charset * @param methodName * @param content * @param params */ private static void setParams(PooledHttpClientHostObject httpClient, HttpMethod method, String contentType, String charset, String methodName, Object content, NativeObject params) { // other parameters have been set, they are properly set to the // corresponding context if (ScriptableObject.getProperty(params, "cookiePolicy") instanceof String) { method.getParams().setCookiePolicy((String) ScriptableObject.getProperty(params, "cookiePolicy")); } else if (!ScriptableObject.getProperty(params, "cookiePolicy").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "contentType") instanceof String) { contentType = (String) ScriptableObject.getProperty(params, "contentType"); } else if (!ScriptableObject.getProperty(params, "contentType").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "charset") instanceof String) { charset = (String) ScriptableObject.getProperty(params, "charset"); } else if (!ScriptableObject.getProperty(params, "charset").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "timeout") instanceof Integer) { method.getParams().setSoTimeout((Integer) ScriptableObject.getProperty(params, "timeout")); } else if (!ScriptableObject.getProperty(params, "timeout").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "doAuthentication") instanceof Boolean) { method.setDoAuthentication((Boolean) ScriptableObject.getProperty(params, "doAuthentication")); } else if (!ScriptableObject.getProperty(params, "doAuthentication").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (ScriptableObject.getProperty(params, "followRedirect") instanceof Boolean) { method.setFollowRedirects((Boolean) ScriptableObject.getProperty(params, "followRedirect")); } else if (!ScriptableObject.getProperty(params, "followRedirect").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } if (methodName.equals("POST")) { // several parameters are specific to POST method if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) { boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked"); ((PostMethod) method).setContentChunked(chuncked); if (chuncked && content != null) { // if contentChucked is set true, then // InputStreamRequestEntity or // MultipartRequestEntity is used if (content instanceof String) { // InputStreamRequestEntity for string content ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity( new ByteArrayInputStream(((String) content).getBytes()))); } else { // MultipartRequestEntity for Name-Value pair // content NativeObject element; List<StringPart> parts = new ArrayList<StringPart>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); parts.add(new StringPart(eName, eValue)); } else { throw new RuntimeException("Invalid content definition, objects of the content" + " array should consists with strings for both key/value"); } } else { throw new RuntimeException( "Invalid content definition, content array should contain " + "Javascript Objects"); } } ((PostMethod) method).setRequestEntity(new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), method.getParams())); } } } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND) && content != null) { // contentChunking has not used if (content instanceof String) { try { ((PostMethod) method) .setRequestEntity(new StringRequestEntity((String) content, contentType, charset)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Charset"); } } else { NativeObject element; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); pairs.add(new NameValuePair(eName, eValue)); } else { throw new RuntimeException( "Invalid content definition, objects of the content array " + "should consists with strings for both key/value"); } } else { throw new RuntimeException("Invalid content definition, content array should contain " + "Javascript Objects"); } } ((PostMethod) method).setRequestBody(pairs.toArray(new NameValuePair[pairs.size()])); } } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } } else if (methodName.equals("GET")) { // here, the method now is GET if (content != null) { if (content instanceof String) { method.setQueryString((String) content); } else { NativeObject element; List<NameValuePair> pairs = new ArrayList<NameValuePair>(); String eName; String eValue; // create pairs using name-value pairs for (int i = 0; i < ((NativeArray) content).getLength(); i++) { if (((NativeArray) content).get(i, (NativeArray) content) instanceof NativeObject) { element = (NativeObject) ((NativeArray) content).get(i, (NativeArray) content); if (ScriptableObject.getProperty(element, "name") instanceof String && ScriptableObject.getProperty(element, "value") instanceof String) { eName = (String) ScriptableObject.getProperty(element, "name"); eValue = (String) ScriptableObject.getProperty(element, "value"); pairs.add(new NameValuePair(eName, eValue)); } else { throw new RuntimeException( "Invalid content definition, objects of the content array " + "should consists with strings for both key/value"); } } else { throw new RuntimeException("Invalid content definition, content array should contain " + "Javascript Objects"); } } method.setQueryString(pairs.toArray(new NameValuePair[pairs.size()])); } } } else if (methodName.equals("PUT")) { // several parameters are specific to PUT method if (ScriptableObject.getProperty(params, "contentChunked") instanceof Boolean) { boolean chuncked = (Boolean) ScriptableObject.getProperty(params, "contentChunked"); ((PutMethod) method).setContentChunked(chuncked); if (chuncked && content != null) { // if contentChucked is set true, then // InputStreamRequestEntity or // MultipartRequestEntity is used if (content instanceof String) { // InputStreamRequestEntity for string content ((PostMethod) method).setRequestEntity(new InputStreamRequestEntity( new ByteArrayInputStream(((String) content).getBytes()))); } else { throw new RuntimeException( "Invalid content definition, content should be a string when PUT " + "method is used"); } } } else if (ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND) && content != null) { // contentChunking has not used if (content instanceof String) { try { ((PostMethod) method) .setRequestEntity(new StringRequestEntity((String) content, contentType, charset)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Charset"); } } else { throw new RuntimeException( "Invalid content definition, content should be a string when PUT " + "method is used"); } } else if (!ScriptableObject.getProperty(params, "contentChunked").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } } // check whether preemptive authentication is used if (ScriptableObject.getProperty(params, "preemptiveAuth") instanceof Boolean) { httpClient.httpClient.getParams() .setAuthenticationPreemptive((Boolean) ScriptableObject.getProperty(params, "preemptiveAuth")); } else if (!ScriptableObject.getProperty(params, "preemptiveAuth").equals(UniqueTag.NOT_FOUND)) { throw new RuntimeException("Method parameters should be Strings"); } }
From source file:smartrics.rest.client.RestClientImpl.java
/** * Configures the instance of HttpMethod with the data in the request and * the host address./* w w w. java 2 s. c om*/ * * @param m * the method class to configure * @param hostAddr * the host address * @param request * the rest request */ protected void configureHttpMethod(HttpMethod m, String hostAddr, final RestRequest request) { addHeaders(m, request); setUri(m, hostAddr, request); m.setQueryString(request.getQuery()); if (m instanceof EntityEnclosingMethod) { RequestEntity requestEntity = null; String fileName = request.getFileName(); if (fileName != null) { requestEntity = configureFileUpload(fileName); } else { fileName = request.getMultipartFileName(); if (fileName != null) { requestEntity = configureMultipartFileUpload(m, request, requestEntity, fileName); } else { requestEntity = new RequestEntity() { public boolean isRepeatable() { return true; } public void writeRequest(OutputStream out) throws IOException { PrintWriter printer = new PrintWriter(out); printer.print(request.getBody()); printer.flush(); } public long getContentLength() { return request.getBody().getBytes().length; } public String getContentType() { List<smartrics.rest.client.RestData.Header> values = request.getHeader("Content-Type"); String v = "text/xml"; if (values.size() != 0) v = values.get(0).getValue(); return v; } }; } } ((EntityEnclosingMethod) m).setRequestEntity(requestEntity); } }
From source file:wuit.common.crawler.WebSit.CrawlerAPIBaiDu.java
/** * HTTP GET?HTML/* w w w.j a v a 2 s . com*/ * * @param url * URL? * @param queryString * ?,?null * @param charset * * @param pretty * ? * @return ?HTML */ public static String doGet(String url, String queryString, String charset, boolean pretty) { StringBuffer response = new StringBuffer(); HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(url); try { if (StringUtils.isNotBlank(queryString)) // get??http?????%? method.setQueryString(URIUtil.encodeQuery(queryString)); client.executeMethod(method); if (method.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader( new InputStreamReader(method.getResponseBodyAsStream(), charset)); String line; while ((line = reader.readLine()) != null) { if (pretty) response.append(line).append(System.getProperty("line.separator")); else response.append(line); } reader.close(); } } catch (URIException e) { log.error("HTTP Get?" + queryString + "???", e); } catch (IOException ex) { Logger.getLogger(CrawlerAPIBaiDu.class.getName()).log(Level.SEVERE, null, ex); } finally { method.releaseConnection(); } return response.toString(); }