List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:org.sdr.webrec.core.WebRec.java
public void run() { initParameters();/* w w w .j ava 2s . c om*/ String transactionName = ""; HttpResponse response = null; DecimalFormat formatter = new DecimalFormat("#####0.00"); DecimalFormatSymbols dfs = formatter.getDecimalFormatSymbols(); formatter.setMinimumFractionDigits(3); formatter.setMaximumFractionDigits(3); // make sure delimeter is a '.' instead of locale default ',' dfs.setDecimalSeparator('.'); formatter.setDecimalFormatSymbols(dfs); do { t1 = System.currentTimeMillis(); URL siteURL = null; try { for (int i = 0; i < url.length; i++) { LOGGER.debug("url:" + ((Transaction) url[i]).getUrl()); Transaction transaction = (Transaction) url[i]; siteURL = new URL(transaction.getUrl()); transactionName = transaction.getName(); //if transaction requires server authentication if (transaction.isAutenticate()) httpclient.getCredentialsProvider().setCredentials( new AuthScope(siteURL.getHost(), siteURL.getPort()), new UsernamePasswordCredentials(transaction.getWorkload().getUsername(), transaction.getWorkload().getPassword())); // Get HTTP GET method httpget = new HttpGet(((Transaction) url[i]).getUrl()); double startTime = System.nanoTime(); double endTime = 0.00d; response = null; // Execute HTTP GET try { response = httpclient.execute(httpget); endTime = System.nanoTime(); } catch (Exception e) { httpget.abort(); LOGGER.error("ERROR in receiving response:" + e.getLocalizedMessage()); e.printStackTrace(); } double timeLapse = 0; if (response != null) { if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { timeLapse = endTime - startTime; LOGGER.debug("starttime:" + (new Double(startTime)).toString()); LOGGER.debug("timeLapse:" + endTime); LOGGER.debug("timeLapse:" + timeLapse); //move nanos to millis timeLapse = timeLapse / 1000000L; LOGGER.debug("response time:" + formatter.format(timeLapse) + "ms."); out.write(System.currentTimeMillis() / 1000 + ":"); out.write( threadName + '.' + transactionName + ":" + formatter.format(timeLapse) + "\n"); //content must be consumed just because //otherwice apache httpconnectionmanager does not release connection back to pool HttpEntity entity = response.getEntity(); if (entity != null) { EntityUtils.toByteArray(entity); } } else { LOGGER.error("Status code of transaction:" + transactionName + " was not " + HttpURLConnection.HTTP_OK + " but " + response.getStatusLine().getStatusCode()); } } int sleepTime = delay; try { LOGGER.debug("Sleeping " + delay / 1000 + "s..."); sleep(sleepTime); } catch (InterruptedException ie) { LOGGER.error("ERROR:" + ie); ie.printStackTrace(); } } } catch (Exception e) { LOGGER.error("Error in thread " + threadName + " with url:" + siteURL + " " + e.getMessage()); e.printStackTrace(); } try { out.flush(); t2 = System.currentTimeMillis(); tTask = t2 - t1; LOGGER.debug("Total time consumed:" + tTask / 1000 + "s."); if (tTask <= interval) { //when task takes less than preset time LOGGER.debug("Sleeping interval:" + (interval - tTask) / 1000 + "s."); sleep(interval - tTask); } cm.closeExpiredConnections(); } catch (InterruptedException ie) { LOGGER.error("Error:" + ie); ie.printStackTrace(); } catch (Exception e) { LOGGER.error("Error:" + e); e.printStackTrace(); } } while (true); }
From source file:org.hyperledger.fabric.sdkintegration.UpdateChannelIT.java
@Test public void setup() { try {//from w ww. j av a 2s . com //////////////////////////// // Setup client //Create instance of client. HFClient client = HFClient.createNewInstance(); client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite()); //////////////////////////// //Set up USERS //Persistence is not part of SDK. Sample file store is for demonstration purposes only! // MUST be replaced with more robust application implementation (Database, LDAP) File sampleStoreFile = new File(System.getProperty("java.io.tmpdir") + "/HFCSampletest.properties"); sampleStoreFile.deleteOnExit(); final SampleStore sampleStore = new SampleStore(sampleStoreFile); //SampleUser can be any implementation that implements org.hyperledger.fabric.sdk.User Interface //////////////////////////// // get users for all orgs for (SampleOrg sampleOrg : testSampleOrgs) { final String orgName = sampleOrg.getName(); sampleOrg.setPeerAdmin(sampleStore.getMember(orgName + "Admin", orgName)); } //////////////////////////// //Reconstruct and run the channels SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg1"); Channel fooChannel = reconstructChannel(FOO_CHANNEL_NAME, client, sampleOrg); // Getting foo channels current configuration bytes. byte[] channelConfigurationBytes = fooChannel.getChannelConfigurationBytes(); HttpClient httpclient = HttpClients.createDefault(); // HttpPost httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/protolator/decode/common.Config"); // httppost.setEntity(new ByteArrayEntity(channelConfigurationBytes)); String responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes); //responseAsString is JSON but use just string operations for this test. if (!responseAsString.contains(ORIGINAL_BATCH_TIMEOUT)) { fail(format("Did not find expected batch timeout '%s', in:%s", ORIGINAL_BATCH_TIMEOUT, responseAsString)); } //Now modify the batch timeout String updateString = responseAsString.replace(ORIGINAL_BATCH_TIMEOUT, UPDATED_BATCH_TIMEOUT); HttpPost httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/protolator/encode/common.Config"); httppost.setEntity(new StringEntity(updateString)); HttpResponse response = httpclient.execute(httppost); int statuscode = response.getStatusLine().getStatusCode(); out("Got %s status for encoding the new desired channel config bytes", statuscode); assertEquals(200, statuscode); byte[] newConfigBytes = EntityUtils.toByteArray(response.getEntity()); // Now send to configtxlator multipart form post with original config bytes, updated config bytes and channel name. httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/configtxlator/compute/update-from-configs"); HttpEntity multipartEntity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody("original", channelConfigurationBytes, ContentType.APPLICATION_OCTET_STREAM, "originalFakeFilename") .addBinaryBody("updated", newConfigBytes, ContentType.APPLICATION_OCTET_STREAM, "updatedFakeFilename") .addBinaryBody("channel", fooChannel.getName().getBytes()).build(); httppost.setEntity(multipartEntity); response = httpclient.execute(httppost); statuscode = response.getStatusLine().getStatusCode(); out("Got %s status for updated config bytes needed for updateChannelConfiguration ", statuscode); assertEquals(200, statuscode); byte[] updateBytes = EntityUtils.toByteArray(response.getEntity()); UpdateChannelConfiguration updateChannelConfiguration = new UpdateChannelConfiguration(updateBytes); //To change the channel we need to sign with orderer admin certs which crypto gen stores: // private key: src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/f1a9a940f57419a18a83a852884790d59b378281347dd3d4a88c2b820a0f70c9_sk //certificate: src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem final String sampleOrgName = sampleOrg.getName(); final SampleUser ordererAdmin = sampleStore.getMember(sampleOrgName + "OrderAdmin", sampleOrgName, "OrdererMSP", Util.findFileSk(Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers() + "/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/") .toFile()), Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers() + "/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem") .toFile()); client.setUserContext(ordererAdmin); //Ok now do actual channel update. fooChannel.updateChannelConfiguration(updateChannelConfiguration, client.getUpdateChannelConfigurationSignature(updateChannelConfiguration, ordererAdmin)); Thread.sleep(3000); // give time for events to happen //Let's add some additional verification... client.setUserContext(sampleOrg.getPeerAdmin()); final byte[] modChannelBytes = fooChannel.getChannelConfigurationBytes(); responseAsString = configTxlatorDecode(httpclient, modChannelBytes); if (!responseAsString.contains(UPDATED_BATCH_TIMEOUT)) { //If it doesn't have the updated time out it failed. fail(format("Did not find updated expected batch timeout '%s', in:%s", UPDATED_BATCH_TIMEOUT, responseAsString)); } if (responseAsString.contains(ORIGINAL_BATCH_TIMEOUT)) { //Should not have been there anymore! fail(format("Found original batch timeout '%s', when it was not expected in:%s", ORIGINAL_BATCH_TIMEOUT, responseAsString)); } assertTrue(eventCountFilteredBlock > 0); // make sure we got blockevent that were tested.updateChannelConfiguration assertTrue(eventCountBlock > 0); // make sure we got blockevent that were tested. //Should be no anchor peers defined. assertFalse(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); assertFalse(responseAsString.matches(REGX_S_ANCHOR_PEERS)); // Get config update for adding an anchor peer. Channel.AnchorPeersConfigUpdateResult configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers( fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), Arrays.asList(PEER_0_ORG_1_EXAMPLE_COM_7051), null); assertNotNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); assertTrue(configUpdateAnchorPeers.getPeersAdded().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); //Now add anchor peer to channel configuration. fooChannel.updateChannelConfiguration(configUpdateAnchorPeers.getUpdateChannelConfiguration(), client.getUpdateChannelConfigurationSignature( configUpdateAnchorPeers.getUpdateChannelConfiguration(), sampleOrg.getPeerAdmin())); Thread.sleep(3000); // give time for events to happen // Getting foo channels current configuration bytes to check with configtxlator channelConfigurationBytes = fooChannel.getChannelConfigurationBytes(); responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes); // Check is anchor peer in config block? assertTrue(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); assertTrue(responseAsString.matches(REGX_S_ANCHOR_PEERS)); //Should see what's there. configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), null, null); assertNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); // not updating anything. assertTrue(configUpdateAnchorPeers.getCurrentPeers().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should be there. assertTrue(configUpdateAnchorPeers.getPeersRemoved().isEmpty()); // not removing any assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything. assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // not updating anyting. //Now remove the anchor peer -- get the config update block. configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), null, Arrays.asList(PEER_0_ORG_1_EXAMPLE_COM_7051)); assertNotNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); assertTrue(configUpdateAnchorPeers.getCurrentPeers().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should still be there. assertTrue(configUpdateAnchorPeers.getPeersRemoved().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer to remove. assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything. assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // no peers should be left. // Now do the actual update. fooChannel.updateChannelConfiguration(configUpdateAnchorPeers.getUpdateChannelConfiguration(), client.getUpdateChannelConfigurationSignature( configUpdateAnchorPeers.getUpdateChannelConfiguration(), sampleOrg.getPeerAdmin())); Thread.sleep(3000); // give time for events to happen // Getting foo channels current configuration bytes to check with configtxlator. channelConfigurationBytes = fooChannel.getChannelConfigurationBytes(); responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes); assertFalse(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); // should be gone! assertTrue(responseAsString.matches(REGX_S_ANCHOR_PEERS)); //ODDLY we still want this even if it's empty! //Should see what's there. configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), null, null); assertNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); // not updating anything. assertTrue(configUpdateAnchorPeers.getCurrentPeers().isEmpty()); // peer should be now gone. assertTrue(configUpdateAnchorPeers.getPeersRemoved().isEmpty()); // not removing any assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything. assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // no peers should be left out("That's all folks!"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:com.micro.utils.H.java
public static byte[] loadImgFromNet(String url, String method) throws Exception { // HttpClient HttpClient client = new DefaultHttpClient(); HttpUriRequest request = null;// w ww . j a va 2 s . c om if ("get".equals(method)) {// get // get request = new HttpGet(url); } else if ("post".equals(method)) {// post request = new HttpPost(url); } // HttpResponse response = client.execute(request); // 2xx:?;3xx:??;4xx:;5xx:? if (response.getStatusLine().getStatusCode() == 200) { // "". HttpEntity entity = response.getEntity(); // ?? // InputStream content = entity.getContent(); return EntityUtils.toByteArray(entity); } return null; }
From source file:org.thevortex.lighting.jinks.icons.WinkIconService.java
/** * Fetch the bytes of the requested image type. * * @param url the location of the image/*from ww w. j a v a 2 s.c o m*/ * @return the fetched bytes or a 0-length array as a place-holder */ private synchronized byte[] getBytes(String url) { CloseableHttpClient httpClient = client.getClient(); try { HttpGet get = new HttpGet(url); try (CloseableHttpResponse response = httpClient.execute(get)) { StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == HttpStatus.SC_OK) { return EntityUtils.toByteArray(response.getEntity()); } logger.error("Response for Icon fetch was {}: {}", statusCode, statusLine.getReasonPhrase()); } } catch (IOException e) { logger.error("Cannot fetch Icon at {}", url, e); } return new byte[0]; }
From source file:org.opcfoundation.ua.transport.https.HttpsClientPendingRequest.java
@Override public void run() { try {//w ww.java 2s . c o m // Abort exit branch if (abortCode != null) { result.setError(new ServiceResultException(abortCode)); return; } // Http Post InetSocketAddress inetAddress = UriUtil.getSocketAddress(httpsClient.connectUrl); String host = inetAddress.getHostName(); int port = inetAddress.getPort(); String scheme = UriUtil.getTransportProtocol(httpsClient.connectUrl); HttpHost httpHost = new HttpHost(host, port, scheme); String url = httpsClient.transportChannelSettings.getDescription().getEndpointUrl(); String endpointId = url == null ? "" : url; //UriUtil.getEndpointName(url); httpPost = new HttpPost(endpointId); httpPost.addHeader("OPCUA-SecurityPolicy", httpsClient.securityPolicyUri); httpPost.addHeader("Content-Type", "application/octet-stream"); // Calculate message length EncoderCalc calc = new EncoderCalc(); calc.setEncoderContext(httpsClient.encoderCtx); calc.putMessage(requestMessage); int len = calc.getLength(); // Assert max size is not exceeded int maxLen = httpsClient.encoderCtx.getMaxMessageSize(); if (maxLen != 0 && len > maxLen) { final EncodingException encodingException = new EncodingException( StatusCodes.Bad_EncodingLimitsExceeded, "MaxStringLength " + maxLen + " < " + len); logger.warn("run: failed", encodingException); throw encodingException; } // Encode message byte[] data = new byte[len]; BinaryEncoder enc = new BinaryEncoder(data); enc.setEncoderContext(httpsClient.encoderCtx); enc.setEncoderMode(EncoderMode.NonStrict); enc.putMessage(requestMessage); httpPost.setEntity(new NByteArrayEntity(data)); // Abort exit branch if (abortCode != null) { result.setError(new ServiceResultException(abortCode)); return; } // Execute Post HttpResponse httpResponse; try { httpResponse = httpsClient.httpclient.execute(httpHost, httpPost); } catch (SSLPeerUnverifiedException e) { // Currently, TLS_1_2 is not supported by JSSE implementations, for some odd reason // and it will give this exception when used. // Also, if the server certificate is rejected, we will get this error result.setError(new ServiceResultException(StatusCodes.Bad_SecurityPolicyRejected, e, "Could not negotiate a TLS security cipher or the server did not provide a valid certificate.")); return; } HttpEntity entity = httpResponse.getEntity(); // Error response int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != 200) { UnsignedInteger uacode = StatusCodes.Bad_UnknownResponse; if (statusCode == 501) uacode = StatusCodes.Bad_ServiceUnsupported; String msg = EntityUtils.toString(entity); result.setError(new ServiceResultException(uacode, statusCode + ": " + msg)); return; } // Abort exit branch if (abortCode != null) { result.setError(new ServiceResultException(abortCode)); return; } // Decode Message data = EntityUtils.toByteArray(entity); BinaryDecoder dec = new BinaryDecoder(data); dec.setEncoderContext(httpsClient.encoderCtx); IEncodeable response = dec.getMessage(); // Client sent an error if (response instanceof ErrorMessage) { ErrorMessage error = (ErrorMessage) response; ServiceResultException errorResult = new ServiceResultException(new StatusCode(error.getError()), error.getReason()); result.setError(errorResult); return; } try { // Client sent a valid message result.setResult((ServiceResponse) response); } catch (ClassCastException e) { result.setError(new ServiceResultException(e)); logger.error("Cannot cast response to ServiceResponse, response=" + response.getClass(), e); } } catch (EncodingException e) { // Internal Error result.setError(new ServiceResultException(StatusCodes.Bad_EncodingError, e)); } catch (ClientProtocolException e) { result.setError(new ServiceResultException(StatusCodes.Bad_CommunicationError, e)); } catch (IOException e) { if (abortCode != null) { result.setError(new ServiceResultException(abortCode, e)); } else { result.setError(new ServiceResultException(StatusCodes.Bad_CommunicationError, e)); } } catch (DecodingException e) { result.setError(new ServiceResultException(StatusCodes.Bad_DecodingError, e)); } catch (ServiceResultException e) { result.setError(e); } catch (RuntimeException rte) { // http-client seems to be throwing these, IllegalArgumentException for one result.setError(new ServiceResultException(rte)); } finally { httpsClient.requests.remove(requestId); } }
From source file:net.peterkuterna.android.apps.devoxxfrsched.util.ImageDownloader.java
Bitmap downloadBitmap(String url) { final int IO_BUFFER_SIZE = 4 * 1024; File cacheFile = null;/*w w w . j av a 2 s. c om*/ try { MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); mDigest.update(url.getBytes()); final String cacheKey = bytesToHexString(mDigest.digest()); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + mContext.getPackageName() + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp"); } } catch (NoSuchAlgorithmException e) { // Oh well, SHA-1 not available (weird), don't cache bitmaps. } HttpGet getRequest = null; try { getRequest = new HttpGet(url); } catch (IllegalArgumentException e) { Log.e(TAG, "Error while constructing get request: " + e.getMessage()); return null; } try { HttpResponse response = mClient.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { final byte[] respBytes = EntityUtils.toByteArray(entity); if (cacheFile != null) { try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } } return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length); } } catch (IOException e) { getRequest.abort(); Log.w(TAG, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w(TAG, "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.w(TAG, "Error while retrieving bitmap from " + url, e); } return null; }
From source file:org.vas.test.rest.RestImpl.java
protected <T> Response<T> extractResponse(Class<T> klass, org.apache.http.client.fluent.Response response) throws Exception { HttpResponse httpResponse = response.returnResponse(); byte[] content = null; try {//from ww w . j a va2 s. co m content = EntityUtils.toByteArray(httpResponse.getEntity()); } catch (IllegalArgumentException e) { if (logger.isDebugEnabled()) { logger.debug("Error when reading entity", e); } } StatusLine statusLine = httpResponse.getStatusLine(); int status = statusLine.getStatusCode(); /* * Short circuit the content extraction if the 401 status has been returned * - by default the response is in HTML for this status so the json parsing * will fail. */ if (status == 401) { return Response.of(status, null, content); } else if (status == 204) { return Response.of(status, null, content); } T body = lookupBody(klass, content); if (body == null) { try { MsgBean msg = GsonUtils.GSON.fromJson(new String(content), MsgBean.class); return Response.of(status, body, content, msg); } catch (JsonSyntaxException e) { logger.warn("Fail to fallback on a MsgBean body", e); } } return Response.of(statusLine.getStatusCode(), body, content); }
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple POST requests with content length * delimited content. //ww w .ja va 2 s .c o m */ @LargeTest public void testSimpleHttpPostsWithContentLength() throws Exception { int reqNo = 20; Random rnd = new Random(); // Prepare some random data List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
From source file:org.webservice.fotolia.FotoliaApi.java
/** * Download a media and write it to a file if necessary * * @param download_url URL as returned by getMedia() * @param output_file if null the downloaded file will be echoed on standard output *//* w ww . ja v a 2s . c o m*/ public void downloadMedia(final String download_url, final String output_file) throws FileNotFoundException, IOException, FotoliaApiException { BufferedOutputStream stream; DefaultHttpClient client; HttpResponse response; StatusLine statusLine; HttpEntity entity; JSONObject obj; String error_msg; int error_code; if (output_file == null) { stream = new BufferedOutputStream(new BufferedOutputStream(System.out)); } else { stream = new BufferedOutputStream(new FileOutputStream(output_file)); } client = this._getHttpClient(true); response = client.execute(new HttpGet(download_url)); statusLine = response.getStatusLine(); entity = response.getEntity(); if (statusLine.getStatusCode() != 200) { if (entity == null) { throw new FotoliaApiException(statusLine.getStatusCode(), statusLine.getReasonPhrase()); } else { obj = (JSONObject) JSONValue.parse(EntityUtils.toString(entity)); error_msg = (String) obj.get("error"); if (obj.get("code") != null) { error_code = Integer.parseInt((String) obj.get("code")); } else { error_code = statusLine.getStatusCode(); } throw new FotoliaApiException(error_code, error_msg); } } stream.write(EntityUtils.toByteArray(entity)); stream.flush(); if (output_file != null) { stream.close(); } }