Java Code Examples for org.apache.http.HttpEntity#writeTo()

The following examples show how to use org.apache.http.HttpEntity#writeTo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestFormBuilder.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected String extract(HttpEntity entity, Header ct, boolean multipart) {
  try {
    if (multipart) {
      String[] pieces = ct.getValue().split("[ ]*[;][ ]*");
      Assert.assertTrue("Wrong content header", pieces[0].equalsIgnoreCase("multipart/form-data"));
    } else {
      Assert.assertTrue("Wrong content header", ct.getValue().equalsIgnoreCase("application/x-www-form-urlencoded"));
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream((int) entity.getContentLength());
    entity.writeTo(out);
    byte[] contents = out.toByteArray();
    String result = new String(contents, HTTPUtil.UTF8);
    return result;
  } catch (IOException e) {
    return null;
  }
}
 
Example 2
Source File: HttpServerTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormParamWithFile() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/testFormParamWithFile", HttpMethod.POST);
    File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    builder.addPart("form", fileBody);
    HttpEntity build = builder.build();
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, file.getName());
}
 
Example 3
Source File: SecretsClientTest.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdate() throws IOException {
    when(mockStatusLine.getStatusCode()).thenReturn(204);
    client.update("scheduler-name/secret-name", PAYLOAD);

    ArgumentCaptor<HttpUriRequest> passedRequest = ArgumentCaptor.forClass(HttpUriRequest.class);
    verify(mockHttpClient).execute(passedRequest.capture(), Mockito.any(HttpContext.class));
    HttpUriRequest request = passedRequest.getValue();

    Assert.assertEquals(request.getMethod(), "PATCH");
    Assert.assertEquals(request.getURI().getPath(), "/secrets/v1/secret/default/scheduler-name/secret-name");

    Assert.assertTrue(request instanceof HttpEntityEnclosingRequest);
    HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();

    Assert.assertEquals(httpEntity.getContentType().getValue(), ContentType.APPLICATION_JSON.toString());

    ByteArrayOutputStream content = new ByteArrayOutputStream();
    httpEntity.writeTo(content);
    JSONObject jsonObject = new JSONObject(content.toString("UTF-8"));

    Assert.assertEquals(jsonObject.getString("value"), PAYLOAD.getValue());
    Assert.assertEquals(jsonObject.getString("author"), PAYLOAD.getAuthor());
    Assert.assertEquals(jsonObject.getString("description"), PAYLOAD.getDescription());
}
 
Example 4
Source File: SecretsClientTest.java    From dcos-commons with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateValidRequest() throws IOException {
    when(mockStatusLine.getStatusCode()).thenReturn(201);

    client.create("scheduler-name/secret-name", PAYLOAD);
    ArgumentCaptor<HttpUriRequest> passedRequest = ArgumentCaptor.forClass(HttpUriRequest.class);
    verify(mockHttpClient).execute(passedRequest.capture(), Mockito.any(HttpContext.class));
    HttpUriRequest request = passedRequest.getValue();

    Assert.assertEquals(request.getMethod(), "PUT");
    Assert.assertEquals(request.getURI().getPath(), "/secrets/v1/secret/default/scheduler-name/secret-name");

    Assert.assertTrue(request instanceof HttpEntityEnclosingRequest);
    HttpEntity httpEntity = ((HttpEntityEnclosingRequest)request).getEntity();

    Assert.assertEquals(httpEntity.getContentType().getValue(), ContentType.APPLICATION_JSON.toString());

    ByteArrayOutputStream content = new ByteArrayOutputStream();
    httpEntity.writeTo(content);
    JSONObject jsonObject = new JSONObject(content.toString("UTF-8"));

    Assert.assertEquals(jsonObject.getString("value"), PAYLOAD.getValue());
    Assert.assertEquals(jsonObject.getString("author"), PAYLOAD.getAuthor());
    Assert.assertEquals(jsonObject.getString("description"), PAYLOAD.getDescription());
}
 
Example 5
Source File: HttpServerTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormDataParamWithComplexForm() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/complexForm", HttpMethod.POST);
    StringBody companyText = new StringBody("{\"type\": \"Open Source\"}", ContentType.APPLICATION_JSON);
    StringBody personList = new StringBody(
            "[{\"name\":\"Richard Stallman\",\"age\":63}, {\"name\":\"Linus Torvalds\",\"age\":46}]",
            ContentType.APPLICATION_JSON);
    HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addTextBody("id", "1")
            .addPart("company", companyText)
            .addPart("people", personList)
            .addBinaryBody("file",
                    new File(Thread.currentThread().getContextClassLoader().getResource("testTxtFile.txt").toURI()),
                           ContentType.DEFAULT_BINARY, "testTxtFile.txt").build();

    connection.setRequestProperty("Content-Type", reqEntity.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        reqEntity.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "testTxtFile.txt:1:2:Open Source");
}
 
Example 6
Source File: HttpServerTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormDataParamWithFileStream() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/streamFile", HttpMethod.POST);
    File file = new File(Thread.currentThread().getContextClassLoader().getResource("testTxtFile.txt").toURI());
    HttpEntity reqEntity = MultipartEntityBuilder.create().
            addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName()).build();

    connection.setRequestProperty("Content-Type", reqEntity.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        reqEntity.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    StringBuilder stringBuilder = new StringBuilder();
    try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
        while (bufferedReader.ready()) {
            stringBuilder.append(bufferedReader.readLine());
        }
    }
    assertEquals(response, stringBuilder.toString() + "-" + file.getName());
}
 
Example 7
Source File: HttpUtil.java    From common-project with Apache License 2.0 6 votes vote down vote up
/**
 * Get方式获取图片
 * 
 * @param url
 * @param path
 *            文件路径
 * @return
 */
public static boolean downloadFile(String url, String path) {
    boolean flag = false;
    HttpClient client = HttpClients.createDefault();
    HttpGet get = new HttpGet(url);
    try {
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        FileOutputStream fos = new FileOutputStream(new File(path));
        entity.writeTo(fos);
        fos.close();
        flag = true;
    } catch (Exception e) {
        logger.error("图片保存失败----", e);
    }
    return flag;
}
 
Example 8
Source File: HttpServerTest.java    From msf4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testFormDataParamWithMultipleFiles() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/multipleFiles", HttpMethod.POST);
    File file1 = new File(Thread.currentThread().getContextClassLoader().getResource("testTxtFile.txt").toURI());
    File file2 = new File(Thread.currentThread().getContextClassLoader().getResource("testPngFile.png").toURI());
    HttpEntity reqEntity = MultipartEntityBuilder.create().
            addBinaryBody("files", file1, ContentType.DEFAULT_BINARY, file1.getName())
            .addBinaryBody("files", file2, ContentType.DEFAULT_BINARY,
                    file2.getName()).build();

    connection.setRequestProperty("Content-Type", reqEntity.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        reqEntity.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "2");
}
 
Example 9
Source File: FileDownLoad.java    From wallpaper with GNU General Public License v2.0 6 votes vote down vote up
public boolean downloadByUrl(String urlString, String fileName) {
	boolean downloadSucceed = false;
	AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null);
	// HttpPost post = new HttpPost(urlString);
	HttpGet get = new HttpGet(urlString);
	HttpResponse response = null;
	try {
		response = httpClient.execute(get);
		if (response.getStatusLine().getStatusCode() == STATUS_OK) {
			HttpEntity entity = response.getEntity();
			File file = mFileHandler.createEmptyFileToDownloadDirectory(fileName);
			entity.writeTo(new FileOutputStream(file));
			downloadSucceed = true;
		} else {
		}

	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		httpClient.close();
	}
	return downloadSucceed;
}
 
Example 10
Source File: HttpClient4EntityExtractor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
/**
 * copy: EntityUtils Get the entity content as a String, using the provided default character set if none is found in the entity. If defaultCharset is null, the default "ISO-8859-1" is used.
 *
 * @param entity         must not be null
 * @param defaultCharset character set to be applied if none found in the entity
 * @return the entity content as a String. May be null if {@link HttpEntity#getContent()} is null.
 * @throws ParseException           if header elements cannot be parsed
 * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
 * @throws IOException              if an error occurs reading the input stream
 */
@SuppressWarnings("deprecation")
private static String entityUtilsToString(final HttpEntity entity, final String defaultCharset, final int maxLength) throws Exception {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity must not be null");
    }
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        return "HTTP entity is too large to be buffered in memory length:" + entity.getContentLength();
    }
    if (entity.getContentType().getValue().startsWith("multipart/form-data")) {
        return "content type is multipart/form-data. content length:" + entity.getContentLength();
    }

    String charset = getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    final FixedByteArrayOutputStream outStream = new FixedByteArrayOutputStream(maxLength);
    entity.writeTo(outStream);
    final String entityValue = outStream.toString(charset);
    if (entity.getContentLength() > maxLength) {
        final StringBuilder sb = new StringBuilder();
        sb.append(entityValue);
        sb.append("HTTP entity large length: ");
        sb.append(entity.getContentLength());
        sb.append(" )");
        return sb.toString();
    }

    return entityValue;
}
 
Example 11
Source File: FhirResourcePatch.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void fhirResourcePatch(String resourceName, String data)
    throws IOException, URISyntaxException {
  // String resourceName =
  //    String.format(
  //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
  // "resource-id");
  // The following data works with a Patient resource and is not intended to work with
  // other types of FHIR resources. If necessary, supply new values for data that
  // correspond to the FHIR resource you are patching.
  // String data = "[{\"op\": \"replace\", \"path\": \"/active\", \"value\": false}]";

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s", client.getRootUrl(), resourceName);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());
  StringEntity requestEntity = new StringEntity(data);

  HttpUriRequest request =
      RequestBuilder.patch(uriBuilder.build())
          .setEntity(requestEntity)
          .addHeader("Content-Type", "application/json-patch+json")
          .addHeader("Accept-Charset", "utf-8")
          .addHeader("Accept", "application/fhir+json; charset=utf-8")
          .build();

  // Execute the request and process the results.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    System.err.print(
        String.format(
            "Exception patching FHIR resource: %s\n", response.getStatusLine().toString()));
    responseEntity.writeTo(System.err);
    throw new RuntimeException();
  }
  System.out.println("FHIR resource patched: ");
  responseEntity.writeTo(System.out);
}
 
Example 12
Source File: ApacheHttpUtils.java    From karate with MIT License 5 votes vote down vote up
public static HttpBody toBody(HttpEntity entity) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        entity.writeTo(baos);
        return HttpBody.bytes(baos.toByteArray(), entity.getContentType().getValue());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }        
}
 
Example 13
Source File: SampleClient.java    From msf4j with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    HttpEntity messageEntity = createMessageForComplexForm();
    // Uncomment the required message body based on the method that want to be used
    //HttpEntity messageEntity = createMessageForMultipleFiles();
    //HttpEntity messageEntity = createMessageForSimpleFormStreaming();

    String serverUrl = "http://localhost:8080/formService/complexForm";
    // Uncomment the required service url based on the method that want to be used
    //String serverUrl = "http://localhost:8080/formService/multipleFiles";
    //String serverUrl = "http://localhost:8080/formService/simpleFormStreaming";

    URL url = URI.create(serverUrl).toURL();
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", messageEntity.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        messageEntity.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    System.out.println(response);

}
 
Example 14
Source File: FhirResourceGetPatientEverything.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void fhirResourceGetPatientEverything(String resourceName)
    throws IOException, URISyntaxException {
  // String resourceName =
  //    String.format(
  //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "patient-id");

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s/$everything", client.getRootUrl(), resourceName);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

  HttpUriRequest request =
      RequestBuilder.get(uriBuilder.build())
          .addHeader("Content-Type", "application/json-patch+json")
          .addHeader("Accept-Charset", "utf-8")
          .addHeader("Accept", "application/fhir+json; charset=utf-8")
          .build();

  // Execute the request and process the results.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    System.err.print(
        String.format(
            "Exception getting patient everythingresource: %s\n",
            response.getStatusLine().toString()));
    responseEntity.writeTo(System.err);
    throw new RuntimeException();
  }
  System.out.println("Patient compartment results: ");
  responseEntity.writeTo(System.out);
}
 
Example 15
Source File: FhirResourceCreate.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void fhirResourceCreate(String fhirStoreName, String resourceType)
    throws IOException, URISyntaxException {
  // String fhirStoreName =
  //    String.format(
  //        FHIR_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-fhir-id");
  // String resourceType = "Patient";

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();
  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s/fhir/%s", client.getRootUrl(), fhirStoreName, resourceType);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());
  StringEntity requestEntity =
      new StringEntity("{\"resourceType\": \"" + resourceType + "\", \"language\": \"en\"}");

  HttpUriRequest request =
      RequestBuilder.post()
          .setUri(uriBuilder.build())
          .setEntity(requestEntity)
          .addHeader("Content-Type", "application/fhir+json")
          .addHeader("Accept-Charset", "utf-8")
          .addHeader("Accept", "application/fhir+json; charset=utf-8")
          .build();

  // Execute the request and process the results.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
    System.err.print(
        String.format(
            "Exception creating FHIR resource: %s\n", response.getStatusLine().toString()));
    responseEntity.writeTo(System.err);
    throw new RuntimeException();
  }
  System.out.print("FHIR resource created: ");
  responseEntity.writeTo(System.out);
}
 
Example 16
Source File: FhirResourceGetHistory.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void fhirResourceGetHistory(String resourceName, String versionId)
    throws IOException, URISyntaxException {
  // String resourceName =
  //    String.format(
  //        FHIR_NAME, "project-id", "region-id", "dataset-id", "store-id", "resource-type",
  // "resource-id");
  // String versionId = "version-uuid"

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s/_history/%s", client.getRootUrl(), resourceName, versionId);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());

  HttpUriRequest request =
      RequestBuilder.get()
          .setUri(uriBuilder.build())
          .addHeader("Content-Type", "application/fhir+json")
          .addHeader("Accept-Charset", "utf-8")
          .addHeader("Accept", "application/fhir+json; charset=utf-8")
          .build();

  // Execute the request and process the results.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    System.err.print(
        String.format(
            "Exception retrieving FHIR history: %s\n", response.getStatusLine().toString()));
    responseEntity.writeTo(System.err);
    throw new RuntimeException();
  }
  System.out.println("FHIR resource retrieved from version: ");
  responseEntity.writeTo(System.out);
}
 
Example 17
Source File: Client.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    String keyStoreLoc = "src/main/config/clientKeystore.jks";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(keyStoreLoc), "cspass".toCharArray());

    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(keyStore, null)
            .loadKeyMaterial(keyStore, "ckpass".toCharArray())
            .useProtocol("TLSv1.2")
            .build();

    /*
     * Send HTTP GET request to query customer info using portable HttpClient
     * object from Apache HttpComponents
     */
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext);

    System.out.println("Sending HTTPS GET request to query customer info");
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sf).build();
    HttpGet httpget = new HttpGet(BASE_SERVICE_URL + "/123");
    BasicHeader bh = new BasicHeader("Accept", "text/xml");
    httpget.addHeader(bh);
    CloseableHttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    entity.writeTo(System.out);
    response.close();
    httpclient.close();

    /*
     *  Send HTTP PUT request to update customer info, using CXF WebClient method
     *  Note: if need to use basic authentication, use the WebClient.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("\n\nSending HTTPS PUT to update customer name");
    WebClient wc = WebClient.create(BASE_SERVICE_URL, CLIENT_CONFIG_FILE);
    Customer customer = new Customer();
    customer.setId(123);
    customer.setName("Mary");
    Response resp = wc.put(customer);

    /*
     *  Send HTTP POST request to add customer, using JAXRSClientProxy
     *  Note: if need to use basic authentication, use the JAXRSClientFactory.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("\n\nSending HTTPS POST request to add customer");
    CustomerService proxy = JAXRSClientFactory.create(BASE_SERVICE_URL, CustomerService.class,
          CLIENT_CONFIG_FILE);
    customer = new Customer();
    customer.setName("Jack");
    resp = wc.post(customer);

    System.out.println("\n");
    System.exit(0);
}
 
Example 18
Source File: FileDownloader.java    From wallpaper with GNU General Public License v2.0 4 votes vote down vote up
public void startDownload() {
	// TODO Auto-generated method stub
	AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null);
	Log.i("kyson", "file url string :"+ mFileUrlString);
	HttpGet get = new HttpGet(mFileUrlString);
	File file = null;
	try {
		HttpResponse response = httpClient.execute(get);
		if (response.getStatusLine().getStatusCode() == STATUS_OK) {
			HttpEntity entity = response.getEntity();
			String fileNameString = MD5Encoder.encoding(mFileUrlString);
			file = FileHandler.shareInstance(WallWrapperApplication.getContext()).createEmptyFileToDownloadDirectory(fileNameString);
			Log.i("kyson", "file is size :"+ file.length());
			entity.writeTo(new FileOutputStream(file));
			if (ERROR_MESSAGE_IMAGESIZEERROR_STRING.length() != entity.getContentLength() ) {
				if (null != mListener) {
					Log.i("kyson", "file is size :"+ mFileUrlString);
					mListener.fileDownloadFininshed(mFileUrlString);
				}else {
					Log.i("kyson", "file is size :"+ "error");
					mListener.fileDownloadFailed(mFileUrlString, ERROR_MESSAGE_IMAGESIZEERROR_STRING);
				}
			}else{
				Log.i("kyson", "file is size :"+ "error");
				mListener.fileDownloadFailed(mFileUrlString, ERROR_MESSAGE_IMAGESIZEERROR_STRING);
			}
			
		} else if (response.getStatusLine().getStatusCode() == 404) {
			if (null != mListener) {
				Log.i("kyson", "file is size :"+ "404");
				mListener.fileDownloadFailed(mFileUrlString, ERROR_MESSAGE_404_STRING);
			}
			//
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		httpClient.close();
		httpClient = null;
	}
}
 
Example 19
Source File: AndroidHttpClient.java    From Alite with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generates a cURL command equivalent to the given request.
 */
private static String toCurl(HttpUriRequest request, boolean logAuthToken) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header: request.getAllHeaders()) {
        if (!logAuthToken
                && (header.getName().equals("Authorization") ||
                    header.getName().equals("Cookie"))) {
            continue;
        }
        builder.append("--header \"");
        builder.append(header.toString().trim());
        builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
        HttpRequest original = ((RequestWrapper) request).getOriginal();
        if (original instanceof HttpUriRequest) {
            uri = ((HttpUriRequest) original).getURI();
        }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest entityRequest =
                (HttpEntityEnclosingRequest) request;
        HttpEntity entity = entityRequest.getEntity();
        if (entity != null && entity.isRepeatable()) {
            if (entity.getContentLength() < 1024) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                entity.writeTo(stream);
                String entityString = stream.toString();

                // TODO: Check the content type, too.
                builder.append(" --data-ascii \"")
                        .append(entityString)
                        .append("\"");
            } else {
                builder.append(" [TOO MUCH DATA TO INCLUDE]");
            }
        }
    }

    return builder.toString();
}
 
Example 20
Source File: HttpMessageHandler.java    From mr4c with Apache License 2.0 4 votes vote down vote up
private String toString(HttpEntity entity) throws IOException {
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	entity.writeTo(out);
	return out.toString();
}