List of usage examples for org.apache.http.client HttpClient getConnectionManager
@Deprecated ClientConnectionManager getConnectionManager();
From source file:hobbyshare.testclient.RestService_TestClient.java
public void test_Login() { HttpClient httpClient = HttpClientBuilder.create().build(); JSONObject loginAttempt = new JSONObject(); loginAttempt.put("password", "1234"); loginAttempt.put("userName", "77_username"); try {// www .j av a 2s . c o m HttpPost request = new HttpPost("http://localhost:8095/login"); StringEntity params = new StringEntity(loginAttempt.toString()); request.addHeader("content-type", "application/json"); request.setEntity(params); HttpResponse response = httpClient.execute(request); System.out.println("---Testing Login----"); System.out.println(response.toString()); HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseString); System.out.println("----End of login Test----"); } catch (Exception ex) { // handle exception here } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:com.wso2telco.dep.verificationhandler.verifier.ACRHandler.java
/** * Gets the msisdn.//from www. j a va2 s.c o m * * @param Url the url * @param Requeststr the requeststr * @return the msisdn * @throws UnsupportedEncodingException the unsupported encoding exception * @throws IOException Signals that an I/O exception has occurred. * @throws JSONException the JSON exception */ private String getMSISDN(String Url, String Requeststr) throws UnsupportedEncodingException, IOException, JSONException { String Authtoken = "con123"; String retStr = ""; log.info("RequestString =" + Requeststr); PoolingClientConnectionManager connManager = new PoolingClientConnectionManager( SchemeRegistryFactory.createDefault()); HttpClient client = new DefaultHttpClient(connManager); //DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(Url); postRequest.addHeader("accept", "application/json"); postRequest.addHeader("authorization", "ServiceKey " + Authtoken); StringEntity input = new StringEntity(Requeststr); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = client.execute(postRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; while ((output = br.readLine()) != null) { retStr += output; } log.info("ACR Response " + retStr); client.getConnectionManager().shutdown(); org.json.JSONObject jsonBody = null; jsonBody = new org.json.JSONObject(retStr.toString()); String msisdn = jsonBody.getJSONObject("decodeAcrResponse").getString("msisdn"); return msisdn; }
From source file:com.autburst.picture.server.HttpRequest.java
public void delete(String sUrl) throws Exception { HttpClient httpclient = new DefaultHttpClient(); try {// w w w . j a v a 2 s . c o m // Prepare a request object HttpDelete httpdelete = new HttpDelete(sUrl); // Execute the request HttpResponse response; response = httpclient.execute(httpdelete); // Examine the response status StatusLine statusLine = response.getStatusLine(); Log.i(TAG, statusLine.toString()); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) throw new Exception("could not perform delete request: " + statusLine.getStatusCode()); } catch (Exception ex) { Log.e(TAG, "---------Error-----" + ex.getMessage()); throw new Exception(ex); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.cgiar.ccafs.ap.util.ClientRepository.java
public DefaultHttpClient verifiedClient(HttpClient base) { try {/*w w w . ja va2 s . c om*/ SSLContext ctx = SSLContext.getInstance("SSL"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager mgr = base.getConnectionManager(); SchemeRegistry registry = mgr.getSchemeRegistry(); registry.register(new Scheme("https", 443, ssf)); return new DefaultHttpClient(mgr, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:DefinitionObject.java
/*** Calls for server output ***/ public void fetch_output(String word) { entry = word;//w w w. j a v a2s . c om System.out.print("----------------\n" + "Word to be defined:\t " + word + "\n----------------"); try { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet getRequest = new HttpGet( "https://api.pearson.com:443/v2/dictionaries/entries?headword=" + word); //Here is word! getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("\nOutput from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); serverOutput = output; } httpClient.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.cottsoft.weedfs.client.WeedfsClient.java
/** * Description<br>/*from ww w . ja va 2 s. c o m*/ * Cache local file to WeedFS Server * * @version v1.0.0 * @param file * @return */ public RequestResult cache(File file) { RequestResult result = null; Gson gson = new Gson(); if (!file.exists()) { throw new IllegalArgumentException("File doesn't exist"); } // HTTP REQUEST begin result = new RequestResult(); WeedAssign assignedInfo = null; BufferedReader in = null; // 1. Send assign request and get fid try { StringBuffer host = new StringBuffer(); host.append("http://"); host.append(this.masterHost); host.append(":"); host.append(this.masterPort); host.append("/"); //HttpUtil.request("http://" + this.masterHost + ":" + this.masterPort+ "/", "dir/assign", "GET") in = new BufferedReader( new InputStreamReader(HttpUtil.request(host.toString(), assign, EHttpMethod.GET))); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } // format HTTP Response to Assigned Info. assignedInfo = gson.fromJson(response.toString(), WeedAssign.class); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } finally { try { // close input stream. if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } // 2. Send cache file request on volume server FileBody fileBody = new FileBody(file, "text/plain"); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); StringBuffer uri = new StringBuffer(); uri.append("http://"); uri.append(assignedInfo.getPublicUrl()); uri.append("/"); uri.append(assignedInfo.getFid()); HttpPost post = new HttpPost(uri.toString()); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("fileBody", fileBody); post.setEntity(entity); try { // Add File char. String response = EntityUtils.toString(client.execute(post).getEntity(), "UTF-8"); client.getConnectionManager().shutdown(); FileResult fileResult = gson.fromJson(response, FileResult.class); result.setFid(assignedInfo.getFid()); result.setSize(fileResult.getSize()); result.setStatus(true); result.setFileUrl(uri.toString()); return result; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.toString()); } }
From source file:ch.entwine.weblounge.test.harness.content.HTMLActionTest.java
/** * Tests whether actions are rendered on pages as configured in module.xml * //from w ww. ja v a 2s .co m * @param serverUrl * the server url */ private void testConfiguredTargetPage(String serverUrl) { logger.info("Preparing test of greeter action"); // Prepare the request logger.info("Testing action target page configuration"); HttpGet request = new HttpGet(UrlUtils.concat(serverUrl, targetedActionPath)); // Send the request and make sure it ends up on the expected page logger.info("Sending request to {}", request.getURI()); HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = TestUtils.request(httpClient, request, null); assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); // Get the document contents Document xml = TestUtils.parseXMLResponse(response); // Make sure it is rendered on the home page String testSuiteTitle = XPathHelper.valueOf(xml, "/html/body/h1"); assertNull("Action is not rendered on configured page", testSuiteTitle); } catch (Throwable e) { fail("Request to " + request.getURI() + " failed" + e.getMessage()); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.trancecode.xproc.step.HttpRequestStepProcessor.java
@Override protected void execute(final StepInput input, final StepOutput output) { final XdmNode sourceDoc = input.readNode(XProcPorts.SOURCE); final XdmNode request = SaxonAxis.childElement(sourceDoc); if (!XProcXmlModel.Elements.REQUEST.equals(request.getNodeName())) { throw XProcExceptions.xc0040(input.getStep().getLocation()); }//from w ww . j a va2s . c om final Map<QName, Object> serializationOptions = Steps.getSerializationOptions(input, DEFAULT_SERIALIZATION_OPTIONS); LOG.trace(" serializationOptions = {}", serializationOptions); final RequestParser parser = new RequestParser(serializationOptions); final Processor processor = input.getPipelineContext().getProcessor(); final XProcHttpRequest xProcRequest = parser.parseRequest(request, processor); final URI uri = xProcRequest.getHttpRequest().getURI(); if (uri.getScheme() != null && !StringUtils.equals("file", uri.getScheme()) && !StringUtils.equals("http", uri.getScheme())) { throw XProcExceptions.xd0012(input.getLocation(), uri.toASCIIString()); } final BasicHttpContext localContext = new BasicHttpContext(); final HttpClient httpClient = prepareHttpClient(xProcRequest, localContext); try { final ResponseHandler<XProcHttpResponse> responseHandler = new HttpResponseHandler(processor, xProcRequest.isDetailled(), xProcRequest.isStatusOnly(), xProcRequest.getOverrideContentType()); final XProcHttpResponse response = httpClient.execute(xProcRequest.getHttpRequest(), responseHandler, localContext); final SaxonBuilder builder = new SaxonBuilder(processor.getUnderlyingConfiguration()); builder.startDocument(); if (response.getNodes() != null) { builder.nodes(response.getNodes()); } builder.endDocument(); output.writeNodes(XProcPorts.RESULT, builder.getNode()); } catch (final IOException e) { // TODO e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:edu.tum.cs.ias.knowrob.BarcodeWebLookup.java
public static String lookUpUpcDatabase(String ean) { String res = ""; if (ean != null && ean.length() > 0) { HttpClient httpclient = new DefaultHttpClient(); try {//from w ww. j ava 2 s. c om HttpGet httpget = new HttpGet("http://www.upcdatabase.com/item/" + ean); httpget.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); // Create a response handler ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; String responseBody = new String(httpclient.execute(httpget, handler), "UTF-8"); // return null if not found if (responseBody.contains("Item Not Found")) return null; else if (responseBody.contains("Item Record")) { // Parse response document Matcher matcher = Pattern.compile("<tr><td>Description<\\/td><td><\\/td><td>(.*)<\\/td><\\/tr>") .matcher(responseBody); if (matcher.find()) { res = matcher.group(1); } } } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } catch (ClientProtocolException cpe) { cpe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } } return res; }
From source file:test.java.ecplugins.weblogic.TestUtils.java
/** * /*from w w w . ja v a 2 s. c om*/ * @return */ static void createCommanderResource(String resourceName, String workspaceName, String resourceIP) throws Exception { props = getProperties(); HttpClient httpClient = new DefaultHttpClient(); JSONObject jo = new JSONObject(); try { HttpPost httpPostRequest = new HttpPost( "http://" + props.getProperty(StringConstants.COMMANDER_SERVER) + ":8000/rest/v1.0/resources/"); String encoding = new String( org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":" + props.getProperty(StringConstants.COMMANDER_PASSWORD)))); jo.put("resourceName", resourceName); jo.put("description", "Resource created for test automation"); jo.put("hostName", resourceIP); jo.put("port", StringConstants.EC_AGENT_PORT); jo.put("workspaceName", workspaceName); jo.put("pools", "default"); jo.put("local", true); StringEntity input = new StringEntity(jo.toString()); input.setContentType("application/json"); httpPostRequest.setEntity(input); httpPostRequest.setHeader("Authorization", "Basic " + encoding); HttpResponse httpResponse = httpClient.execute(httpPostRequest); if (httpResponse.getStatusLine().getStatusCode() == 409) { System.out.println("Commander resource already exists.Continuing...."); } else if (httpResponse.getStatusLine().getStatusCode() >= 400) { throw new RuntimeException( "Failed to create commander workspace " + httpResponse.getStatusLine().getStatusCode() + "-" + httpResponse.getStatusLine().getReasonPhrase()); } } finally { httpClient.getConnectionManager().shutdown(); } }