List of usage examples for org.apache.http.client HttpClient getConnectionManager
@Deprecated ClientConnectionManager getConnectionManager();
From source file:ClientWithResponseHandler.java
public void sub() throws Exception { HttpClient httpclient = new DefaultHttpClient(); try {/* w w w.j a v a2 s.com*/ HttpGet httpget = new HttpGet("https://www.google.com/m8/feeds/contacts/default/full/"); httpget.addHeader("Authorization", "OAuth ya29.AHES6ZRPmOdPH5NegD3vQByXUe_1L2ikXZEbECGPEkwXiDxzPLg9oi8"); httpget.addHeader("Gdata-version", "3.0"); System.out.println("executing request " + httpget.getURI()); Header[] headers = httpget.getAllHeaders(); for (Header temp : headers) { System.out.println(temp.getName()); } // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); System.out.println("----------------------------------------"); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:co.forsaken.api.json.JsonWebCall.java
public void execute(Object arg) { if (_log)//from w ww . j ava 2 s . c om System.out.println("Requested: [" + _url + "]"); try { canConnect(); } catch (Exception ex) { ex.printStackTrace(); return; } HttpClient httpClient = new DefaultHttpClient(_connectionManager); try { Gson gson = new Gson(); HttpPost request = new HttpPost(_url); if (arg != null) { StringEntity params = new StringEntity(gson.toJson(arg)); params.setContentType(new BasicHeader("Content-Type", "application/json")); request.setEntity(params); } httpClient.execute(request); } catch (Exception ex) { System.out.println("JSONWebCall.executeNoRet() Error: \n" + ex.getMessage()); StackTraceElement[] arrOfSTE; int max = (arrOfSTE = ex.getStackTrace()).length; for (int i = 0; i < max; i++) { StackTraceElement trace = arrOfSTE[i]; System.out.println(trace); } } finally { httpClient.getConnectionManager().shutdown(); } if (_log) System.out.println("Returned: [" + _url + "]"); }
From source file:ecplugins.websphere.TestUtils.java
/** * * @return//from ww w. j a v a 2s .c om */ static void createCommanderResource() throws Exception { if (!isCommanderResourceCreatedSuccessfully) { // If CommanderResource not created before HttpClient httpClient = new DefaultHttpClient(); JSONObject jo = new JSONObject(); try { HttpPost httpPostRequest = new HttpPost( "http://" + props.getProperty(StringConstants.COMMANDER_USER) + ":" + props.getProperty(StringConstants.COMMANDER_PASSWORD) + "@" + StringConstants.COMMANDER_SERVER + ":8000/rest/v1.0/resources/"); jo.put("resourceName", StringConstants.RESOURCE_NAME); jo.put("description", "Resource created for test automation"); jo.put("hostName", props.getProperty(StringConstants.WEBSPHERE_AGENT_IP)); jo.put("port", props.getProperty(StringConstants.WEBSPHERE_AGENT_PORT)); jo.put("workspaceName", StringConstants.WORKSPACE_NAME); jo.put("pools", "default"); jo.put("local", true); StringEntity input = new StringEntity(jo.toString()); input.setContentType("application/json"); httpPostRequest.setEntity(input); 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()); } // Indicate successful creation commander resource. isCommanderResourceCreatedSuccessfully = true; } finally { httpClient.getConnectionManager().shutdown(); } } }
From source file:ch.uzh.ifi.attempto.ape.APEWebservice.java
private String getEntity(HttpClient httpclient, HttpUriRequest httpRequest) { try {// w w w . j a v a2s . c o m HttpResponse response = httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); if (entity == null) { throw new RuntimeException(ERROR_MESSAGE + ": " + response.getStatusLine()); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException(ERROR_MESSAGE + ": " + response.getStatusLine()); } // The APE webservice returns the data in UTF8, even if it doesn't declare it. if (entity.getContentEncoding() == null) { return EntityUtils.toString(entity, HTTP.UTF_8); } return EntityUtils.toString(entity); } catch (ClientProtocolException e) { throw new RuntimeException(ERROR_MESSAGE + ": " + e.getMessage()); } catch (IOException e) { throw new RuntimeException(ERROR_MESSAGE + ": " + e.getMessage()); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:com.penbase.dma.Dalyo.HTTPConnection.DmaHttpClient.java
/** * Manages post services/* w w w .j a va 2 s.c om*/ * @param parameters * @return */ public byte[] sendPost(String parameters) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); HttpClient httpClient = new DefaultHttpClient(); // HttpPost httpPost = new HttpPost(Constant.SECUREDSERVER + // parameters); HttpPost httpPost = new HttpPost(Constant.SERVER + parameters); try { HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); int c; byte[] readByte = new byte[32 * 1024]; while ((c = in.read(readByte)) > 0) { bos.write(readByte, 0, c); } in.close(); httpPost.abort(); httpClient.getConnectionManager().shutdown(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (bos.size() > 0) { byte[] data = bos.toByteArray(); String codeStr = ""; int i = 0; int length = data.length; while (i < length && data[i] != (int) '\n') { codeStr += (char) data[i]; i++; } mErrorCode = Integer.valueOf(codeStr); if (mErrorCode != ErrorCode.OK) { return null; } else { int newLength = data.length - codeStr.length() - 1; byte[] result = new byte[newLength]; System.arraycopy(data, codeStr.length() + 1, result, 0, result.length); return result; } } else { return null; } }
From source file:ch.entwine.weblounge.test.harness.content.JavaServerPagesTest.java
/** * {@inheritDoc}//w ww . ja v a2 s. c om * * @see ch.entwine.weblounge.testing.kernel.IntegrationTest#execute(java.lang.String) */ @Override public void execute(String serverUrl) throws Exception { logger.info("Testing loading of java server page"); String requestUrl = UrlUtils.concat(serverUrl, JSP_PATH); HttpGet request = new HttpGet(requestUrl); logger.info("Sending request to {}", requestUrl); // Send and the request and examine the response HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = TestUtils.request(httpClient, request, null); assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); String contentType = response.getEntity().getContentType().getValue(); assertEquals(CONTENT_TYPE_HTML, contentType.split(";")[0]); // Test template contents Document xml = TestUtils.parseXMLResponse(response); String templateOutput = XPathHelper.valueOf(xml, "/html/head/title"); assertNotNull("General template output does not work", templateOutput); assertEquals("Template title is not as expected", "Weblounge Test Site", templateOutput); // Test site tag libraries logger.info("Testing weblounge taglibrary on {}", requestUrl); String generator = "/html/head/meta[@name='generator']/@content"; Assert.assertNotNull("Generator tag not found", XPathHelper.valueOf(xml, generator)); Assert.assertNotNull("Weblounge 3.0", XPathHelper.valueOf(xml, generator)); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:fib.lcfib.raco.Controladors.ControladorLoginRaco.java
private void showAddDialog() { loginDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); loginDialog.setTitle(R.string.loginRaco); LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View dialogView = li.inflate(R.layout.contingut_login, null); loginDialog.setContentView(dialogView); username = (EditText) dialogView.findViewById(R.id.login); password = (EditText) dialogView.findViewById(R.id.password); Button okButton = (Button) dialogView.findViewById(R.id.acceptar_button); Button cancelButton = (Button) dialogView.findViewById(R.id.cancel_button); loginDialog.setCancelable(false);/*from w w w . ja v a 2 s.c o m*/ loginDialog.show(); okButton.setOnClickListener(new OnClickListener() { // @Override public void onClick(View v) { try { String usernameAux = username.getText().toString().trim(); String passwordAux = password.getText().toString().trim(); usernameAux = URLEncoder.encode(usernameAux, "UTF-8"); passwordAux = URLEncoder.encode(passwordAux, "UTF-8"); boolean correcte = check_user(usernameAux, passwordAux); if (correcte) { Toast.makeText(getApplicationContext(), R.string.login_correcte, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), R.string.errorLogin, Toast.LENGTH_LONG).show(); } if ("zonaRaco".equals(queEs)) { Intent intent = new Intent(ControladorLoginRaco.this, ControladorTabIniApp.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("esLogin", "zonaRaco"); startActivity(intent); } else { Intent act = new Intent(ControladorLoginRaco.this, ControladorTabIniApp.class); // Aquestes 2 lnies provoquen una excepci per no peta // simplement informa s normal act.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); act.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(act); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } private boolean check_user(String username, String password) { GestorCertificats.allowAllSSL(); AndroidUtils au = AndroidUtils.getInstance(); /** open connection */ //Aix tanquem les connexions segur System.setProperty("http.keepAlive", "false"); try { InputStream is = null; HttpGet request = new HttpGet(au.URL_LOGIN + "username=" + username + "&password=" + password); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Header[] headers = response.getHeaders("Location"); if (headers != null && headers.length != 0) { String newUrl = headers[headers.length - 1].getValue(); request = new HttpGet(newUrl); client.execute(request); } } /** Get Keys */ is = response.getEntity().getContent(); ObjectMapper m = new ObjectMapper(); JsonNode rootNode = m.readValue(is, JsonNode.class); is.close(); client.getConnectionManager().closeExpiredConnections(); if (rootNode.isNull()) { return false; } else { // GenerarUrl(); /** calendari ics */ String KEYportadaCal = rootNode.path("/ical/portada.ics").getTextValue().toString(); /** calendari rss */ String KEYportadaRss = rootNode.path("/ical/portada.rss").getTextValue().toString(); /** Avisos */ String KEYavisos = rootNode.path("/extern/rss_avisos.jsp").getTextValue().toString(); /** Assigraco */ String KEYAssigRaco = rootNode.path("/api/assigList").getTextValue().toString(); /** Horari */ String KEYIcalHorari = rootNode.path("/ical/horari.ics").getTextValue().toString(); /**Notificacions */ String KEYRegistrar = rootNode.path("/api/subscribeNotificationSystem").getTextValue() .toString(); String KEYDesregistrar = rootNode.path("/api/unsubscribeNotificationSystem").getTextValue() .toString(); SharedPreferences sp = getSharedPreferences(PreferenciesUsuari.getPreferenciesUsuari(), MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); /** Save Username and Password */ editor.putString(AndroidUtils.USERNAME, username); editor.putString(AndroidUtils.PASSWORD, password); /** Save Keys */ editor.putString(au.KEY_AGENDA_RACO_XML, KEYportadaRss); editor.putString(au.KEY_AGENDA_RACO_CAL, KEYportadaCal); editor.putString(au.KEY_AVISOS, KEYavisos); editor.putString(au.KEY_ASSIG_FIB, "public"); editor.putString(au.KEY_ASSIGS_RACO, KEYAssigRaco); editor.putString(au.KEY_HORARI_RACO, KEYIcalHorari); editor.putString(au.KEY_NOTIFICACIONS_REGISTRAR, KEYRegistrar); editor.putString(au.KEY_NOTIFICACIONS_DESREGISTRAR, KEYDesregistrar); /** Save changes */ editor.commit(); } return true; } catch (ProtocolException e) { Toast.makeText(getApplicationContext(), R.string.errorLogin, Toast.LENGTH_LONG).show(); return false; } catch (IOException e) { Toast.makeText(getApplicationContext(), R.string.errorLogin, Toast.LENGTH_LONG).show(); return false; } } }); cancelButton.setOnClickListener(new OnClickListener() { // @Override public void onClick(View v) { Intent act = new Intent(ControladorLoginRaco.this, ControladorTabIniApp.class); act.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); act.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(act); } }); }
From source file:org.csware.ee.utils.Tools.java
public static String getCarValue(String path, String carUrl) { String json = null;//from w w w.ja v a 2s .c om InputStream is = null; HttpClient hc = new DefaultHttpClient(); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("carUrl", carUrl)); HttpPost post = new HttpPost(path); UrlEncodedFormEntity entity; HttpResponse response = null; try { entity = new UrlEncodedFormEntity(formparams, "UTF-8"); post.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml"); post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3"); post.addHeader("Accept-Encoding", "gzip,deflate,sdch"); post.addHeader("Connection", "Keep-Alive"); post.addHeader("Cache-Control", "no-cache"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(entity); response = hc.execute(post); System.out.println(response.getStatusLine().getStatusCode()); HttpEntity e = response.getEntity(); if (200 == response.getStatusLine().getStatusCode()) { if (!e.equals(null)) { json = EntityUtils.toString(e); } System.out.println("?"); } else { System.out.println(""); } hc.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); } return json; }
From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyServer.java
@Override public String get(String keyIdHex) throws QueryException { HttpClient client = new DefaultHttpClient(); try {//from ww w .j av a 2 s .co m String query = "http://" + mHost + ":" + mPort + "/pks/lookup?op=get&options=mr&search=" + keyIdHex; Log.d(Constants.TAG, "hkp keyserver get: " + query); HttpGet get = new HttpGet(query); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new QueryException("not found"); } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); String data = readAll(is, EntityUtils.getContentCharSet(entity)); Matcher matcher = PgpHelper.PGP_PUBLIC_KEY.matcher(data); if (matcher.find()) { return matcher.group(1); } } catch (IOException e) { // nothing to do, better luck on the next keyserver } finally { client.getConnectionManager().shutdown(); } return null; }
From source file:org.csware.ee.utils.Tools.java
public static String getDriverValue(String path, String carUrl) { String json = null;/*from w w w . ja va2 s . c om*/ InputStream is = null; HttpClient hc = new DefaultHttpClient(); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("driverUrl", carUrl)); HttpPost post = new HttpPost(path); UrlEncodedFormEntity entity; HttpResponse response = null; try { entity = new UrlEncodedFormEntity(formparams, "UTF-8"); post.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml"); post.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3"); post.addHeader("Accept-Encoding", "gzip,deflate,sdch"); post.addHeader("Connection", "Keep-Alive"); post.addHeader("Cache-Control", "no-cache"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(entity); response = hc.execute(post); System.out.println(response.getStatusLine().getStatusCode()); HttpEntity e = response.getEntity(); if (200 == response.getStatusLine().getStatusCode()) { if (!e.equals(null)) { json = EntityUtils.toString(e); } System.out.println("?"); } else { System.out.println(""); } hc.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); } return json; }