List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager
public synchronized final ClientConnectionManager getConnectionManager()
From source file:org.picketbox.test.jaxrs.RESTEasyStandaloneTestCase.java
/** * This testcase tests that a regular non-json payload is returned without any encryption * * @throws Exception/*from w w w .j a v a2s.c o m*/ */ @Test public void testPlainText() throws Exception { String urlStr = "http://localhost:11080/rest/bookstore/books"; URL url = new URL(urlStr); DefaultHttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url.toExternalForm()); httpget.setHeader(JWEInterceptor.CLIENT_ID, "1234"); System.out.println("executing request:" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); StatusLine statusLine = response.getStatusLine(); System.out.println(statusLine); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } InputStream is = entity.getContent(); String contentString = getContentAsString(is); System.out.println("Plain Text=" + contentString); assertNotNull(contentString); assertEquals("books=Les Miserables", contentString); assertEquals(200, statusLine.getStatusCode()); EntityUtils.consume(entity); } 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:se.vgregion.incidentreport.pivotaltracker.impl.PivotalTrackerServiceImpl.java
public String addStoryForProject(String projectId, PTStory story) { String token = getUserToken(ptUser, ptPwd); DefaultHttpClient client = getNewClient(); String result = null;/*from w ww . j a v a 2 s . com*/ String xml = "<story><story_type>" + story.getType() + "</story_type><name>" + story.getName() + "</name>" + "<description>" + story.getDescription() + "</description><requested_by>" + story.getRequestedBy() + "</requested_by></story>"; try { HttpResponse response = HTTPUtils.makePostXML(GET_PROJECT + "/" + projectId + "/stories", token, client, xml); HttpEntity entity = response.getEntity(); String xmlout = convertStreamToString(entity.getContent()); // System.out.println(xmlout); String url = getTagValue(xmlout, 0, "url"); story.setProjectId(projectId); int sidIndex = url.lastIndexOf("/"); String storyId = url.substring(sidIndex + 1); story.setStoryId(storyId); result = url; // Convert the xml response into an object // result = getProjectData((entity.getContent())); } catch (Exception e) { throw new RuntimeException("Failed to add story to PivotalTracker", e); } finally { client.getConnectionManager().shutdown(); } return result; }
From source file:org.jboss.as.test.clustering.cluster.web.NonHaWebSessionPersistenceTestCase.java
@Test @OperateOnDeployment(DEPLOYMENT_1)/*w w w .j av a 2 s . c o m*/ public void testSessionPersistence( @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL) throws IOException { DefaultHttpClient client = new DefaultHttpClient(); String url = baseURL.toString() + "simple"; try { HttpResponse response = client.execute(new HttpGet(url)); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue())); response.getEntity().getContent().close(); response = client.execute(new HttpGet(url)); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue())); Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue())); response.getEntity().getContent().close(); stop(CONTAINER_SINGLE); start(CONTAINER_SINGLE); response = client.execute(new HttpGet(url)); Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals("Session passivation was configured but session was lost after restart.", 3, Integer.parseInt(response.getFirstHeader("value").getValue())); Assert.assertTrue(Boolean.valueOf(response.getFirstHeader("serialized").getValue())); response.getEntity().getContent().close(); } finally { client.getConnectionManager().shutdown(); } }
From source file:sand.actionhandler.weibo.UdaClient.java
public static String downloadImageImpl(String server, String url) { boolean ret = false; DefaultHttpClient httpclient = new DefaultHttpClient(); try {//from w w w.j av a 2 s . c o m if (url.charAt(0) == '/') url = url.substring(1); File storeFile = new File("/root/udaclient/build/" + url); if (ActionHandler.OS_TYPE.equalsIgnoreCase("windows")) { storeFile = new File(_windowsLocation + url); } //File storeFile = new File("c:/root/udaclient/build/"+url); //?? if (storeFile.exists()) { return "exists"; } httpclient = createHttpClient(); HttpGet httpget = new HttpGet(server + url); // Execute HTTP request // System.out.println("executing request " + httpget.getURI()); //logger.info("executing request " + httpget.getURI()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity.getContentType().getValue().indexOf("text/html") >= 0) { return "error"; } // org.apache.commons.io.FileUtils.touch(storeFile); FileOutputStream fileOutputStream = new FileOutputStream(storeFile); FileOutputStream output = fileOutputStream; entity.writeTo(output); output.close(); ret = true; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return "success"; }
From source file:immf.AppNotifications.java
private void send(String message, String command) throws Exception { String url = PushUrl;/*from w ww . j a v a 2s. com*/ DefaultHttpClient httpClient = new DefaultHttpClient(); // appnotifications?DNS???IP?? // ??SSL??????????? if (dnsCache) { InetAddress ipaddr; try { ipaddr = InetAddress.getByName(PushHost); this.pushaddr = ipaddr; } catch (UnknownHostException e) { if (pushaddr != null) { log.warn("DNS lookup error, using cache..."); ipaddr = this.pushaddr; } else { throw (e); } } SSLSocketFactory sf = SSLSocketFactory.getSocketFactory(); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sc = new Scheme("https", sf, 443); httpClient.getConnectionManager().getSchemeRegistry().register(sc); url = "https://" + ipaddr.getHostAddress() + PushPath; } HttpPost post = new HttpPost(url); post.setHeader("Host", PushHost); // dnsCache List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("user_credentials", this.credentials)); if (!this.sound.isEmpty()) { formparams.add(new BasicNameValuePair("notification[sound]", this.sound)); } formparams.add(new BasicNameValuePair("notification[message]", message)); formparams.add(new BasicNameValuePair("notification[icon_url]", this.iconUrl)); formparams.add(new BasicNameValuePair("notification[message_level]", "2")); formparams.add(new BasicNameValuePair("notification[silent]", "0")); if (command != null && !command.isEmpty()) { // ??????action_loc_key??? formparams.add(new BasicNameValuePair("notification[action_loc_key]", "Reply")); formparams.add(new BasicNameValuePair("notification[run_command]", command)); } else { formparams.add(new BasicNameValuePair("notification[action_loc_key]", "")); } UrlEncodedFormEntity entity = null; try { entity = new UrlEncodedFormEntity(formparams, "UTF-8"); } catch (Exception e) { } post.setEntity(entity); try { HttpResponse res = httpClient.execute(post); int status = res.getStatusLine().getStatusCode(); if (status != 200) { if (status >= 500) { throw new MyHttpException("http server error. status=" + status); } else { throw new Exception("http server error. status=" + status); } } String resString = EntityUtils.toString(res.getEntity()); log.info("?:" + resString); JSONObject json = JSONObject.fromObject(resString); int id = json.getInt("id"); if (id < 1) { throw new Exception("illegal id returned"); } } catch (JSONException e) { /* * (1)JSONObject.fromObject?exception???post? * (2)id????????? * (????? {"Response":"Not Authorized"} ??HTTP?status?401??) */ throw new Exception("wrong request"); } finally { post.abort(); } }
From source file:ADP_Streamline.CURL2.java
public String uploadFiles(File file, String siteId, String containerId, String uploadDirectory) { String json = null;/*from ww w. j av a2s. c o m*/ DefaultHttpClient httpclient = new DefaultHttpClient(); HttpHost targetHost = new HttpHost("localhost", 8080, "http"); try { HttpPost httppost = new HttpPost("/alfresco/service/api/upload?alf_ticket=" + this.ticket); FileBody bin = new FileBody(file); StringBody siteid = new StringBody(siteId); StringBody containerid = new StringBody(containerId); StringBody uploaddirectory = new StringBody(uploadDirectory); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("filedata", bin); reqEntity.addPart("siteid", siteid); reqEntity.addPart("containerid", containerid); reqEntity.addPart("uploaddirectory", uploaddirectory); httppost.setEntity(reqEntity); //log.debug("executing request:" + httppost.getRequestLine()); HttpResponse response = httpclient.execute(targetHost, httppost); HttpEntity resEntity = response.getEntity(); //log.debug("response status:" + response.getStatusLine()); if (resEntity != null) { //log.debug("response content length:" + resEntity.getContentLength()); json = EntityUtils.toString(resEntity); //log.debug("response content:" + json); } EntityUtils.consume(resEntity); } catch (Exception e) { throw new RuntimeException(e); } finally { httpclient.getConnectionManager().shutdown(); } return json; }
From source file:ch.tatool.app.export.ServerDataExporter.java
private String uploadFiles(Component parentFrame, Module module, HttpEntity httpEntity) { // get the server upload configuration String serverUrl = getUrl();/*from w w w. j ava 2s . co m*/ if (serverUrl == null) { exporterError.setErrorType(DataExporterError.SERVER_ONLINE_URL_MISSING); return "Reason: No upload server url defined"; } String username = module.getModuleProperties().get(PROPERTY_EXPORT_USERNAME); if (username == null) { username = "anonymous"; } String password = module.getModuleProperties().get(PROPERTY_EXPORT_PASSWORD); if (password == null) { password = "anonymous"; } HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 0); // Create a httpclient instance DefaultHttpClient httpclient = new DefaultHttpClient(params); // set the credentials we got (might or might not get used //httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); // setup a POST call HttpPost httpPost = new HttpPost(serverUrl); httpPost.setEntity(httpEntity); // execute the post and gather the result try { HttpResponse response = httpclient.execute(httpPost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { exporterError.setErrorType(DataExporterError.SERVER_ONLINE_HTTP); exporterError.setErrorReason(response.getStatusLine().getReasonPhrase() + " (" + response.getStatusLine().getStatusCode() + ")"); return "Reason: " + response.getStatusLine().getReasonPhrase() + " (" + response.getStatusLine().getStatusCode() + ")"; } else { // all ok String result = IOUtils.toString(response.getEntity().getContent()); if (logger.isDebugEnabled()) { logger.debug("Upload server response: {}", result); } } } catch (IOException ioe) { httpclient.getConnectionManager().shutdown(); logger.error("Unable to upload data", ioe); exporterError.setErrorType(DataExporterError.GENERAL_UNKNOWN); exporterError.setErrorReason(ioe.toString() + ": " + ioe.getMessage()); return "Reason: " + ioe.toString() + ": " + ioe.getMessage(); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return null; }
From source file:test.gov.nih.nci.cacoresdk.domain.manytomany.bidirectional.selfassociation.MemberM2MBSResourceTest.java
public void testPut() throws Exception { try {//w w w . j a v a2 s. c o m DefaultHttpClient httpClient = new DefaultHttpClient(); String url = baseURL + "/rest/MemberM2MBS"; HttpPut putRequest = new HttpPut(url); File myFile = new File("MemberM2MBS" + "XML.xml"); if (!myFile.exists()) { testGet(); myFile = new File("MemberM2MBS" + "XML.xml"); if (!myFile.exists()) return; } FileEntity input = new FileEntity(myFile); input.setContentType("application/xml"); putRequest.setEntity(input); HttpResponse response = httpClient.execute(putRequest); if (response.getEntity() != null) { BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } } httpClient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); throw e; } }
From source file:test.gov.nih.nci.cacoresdk.domain.onetoone.bidirectional.selfassociation.MemberO2OBSResourceTest.java
public void testPut() throws Exception { try {//from w w w. ja v a2 s . c o m DefaultHttpClient httpClient = new DefaultHttpClient(); String url = baseURL + "/rest/MemberO2OBS"; HttpPut putRequest = new HttpPut(url); File myFile = new File("MemberO2OBS" + "XML.xml"); if (!myFile.exists()) { testGet(); myFile = new File("MemberO2OBS" + "XML.xml"); if (!myFile.exists()) return; } FileEntity input = new FileEntity(myFile); input.setContentType("application/xml"); putRequest.setEntity(input); HttpResponse response = httpClient.execute(putRequest); if (response.getEntity() != null) { BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } } httpClient.getConnectionManager().shutdown(); } catch (Exception e) { e.printStackTrace(); throw e; } }
From source file:net.java.sip.communicator.impl.protocol.sip.xcap.BaseHttpXCapClient.java
/** * Puts the resource to the server./*from www.ja v a2s .c o m*/ * * @param resource the resource to be saved on the server. * @return the server response. * @throws IllegalStateException if the user has not been connected. * @throws XCapException if there is some error during operation. */ public XCapHttpResponse put(XCapResource resource) throws XCapException { DefaultHttpClient httpClient = null; try { httpClient = createHttpClient(); URI resourceUri = getResourceURI(resource.getId()); HttpPut putMethod = new HttpPut(resourceUri); putMethod.setHeader("Connection", "close"); StringEntity stringEntity = new StringEntity(resource.getContent()); stringEntity.setContentType(resource.getContentType()); stringEntity.setContentEncoding("UTF-8"); putMethod.setEntity(stringEntity); if (logger.isDebugEnabled()) { String logMessage = String.format("Puting resource %1s to the server %2s", resource.getId().toString(), resource.getContent()); logger.debug(logMessage); } HttpResponse response = httpClient.execute(putMethod); return createResponse(response); } catch (IOException e) { String errorMessage = String.format("%1s resource cannot be put", resource.getId().toString()); throw new XCapException(errorMessage, e); } finally { if (httpClient != null) httpClient.getConnectionManager().shutdown(); } }