Beispiel #1
0
 public HttpResponse post(String uri, InputStream content) {
   InputStreamEntity e = new InputStreamEntity(content, -1);
   e.setContentType("application/json");
   HttpPost post = new HttpPost(uri);
   post.setEntity(e);
   return executeRequest(post, true);
 }
Beispiel #2
0
  public HttpResponse put(String uri, InputStream data, String contentType, long contentLength) {
    InputStreamEntity e = new InputStreamEntity(data, contentLength);
    e.setContentType(contentType);

    HttpPut hp = new HttpPut(uri);
    hp.setEntity(e);
    return executeRequest(hp);
  }
  @Override
  public void storeItem(final ProxyRepository repository, final StorageItem item)
      throws UnsupportedStorageOperationException, RemoteStorageException {
    if (!(item instanceof StorageFileItem)) {
      throw new UnsupportedStorageOperationException(
          "Storing of non-files remotely is not supported!");
    }

    final StorageFileItem fileItem = (StorageFileItem) item;

    final ResourceStoreRequest request = new ResourceStoreRequest(item);

    final URL remoteUrl =
        appendQueryString(getAbsoluteUrlFromBase(repository, request), repository);

    final HttpPut method = new HttpPut(remoteUrl.toExternalForm());

    final InputStreamEntity entity;
    try {
      entity = new InputStreamEntity(fileItem.getInputStream(), fileItem.getLength());
    } catch (IOException e) {
      throw new RemoteStorageException(
          e.getMessage()
              + " [repositoryId=\""
              + repository.getId()
              + "\", requestPath=\""
              + request.getRequestPath()
              + "\", remoteUrl=\""
              + remoteUrl.toString()
              + "\"]",
          e);
    }

    entity.setContentType(fileItem.getMimeType());
    method.setEntity(entity);

    final HttpResponse httpResponse = executeRequestAndRelease(repository, request, method);
    final int statusCode = httpResponse.getStatusLine().getStatusCode();

    if (statusCode != HttpStatus.SC_OK
        && statusCode != HttpStatus.SC_CREATED
        && statusCode != HttpStatus.SC_NO_CONTENT
        && statusCode != HttpStatus.SC_ACCEPTED) {
      throw new RemoteStorageException(
          "Unexpected response code while executing "
              + method.getMethod()
              + " method [repositoryId=\""
              + repository.getId()
              + "\", requestPath=\""
              + request.getRequestPath()
              + "\", remoteUrl=\""
              + remoteUrl.toString()
              + "\"]. Expected: \"any success (2xx)\". Received: "
              + statusCode
              + " : "
              + httpResponse.getStatusLine().getReasonPhrase());
    }
  }
 public void putStream(String feedUrl, InputStream stream, String contentType, Operation operation)
     throws IOException {
   InputStreamEntity entity = new InputStreamEntity(stream, -1);
   entity.setContentType(contentType);
   HttpPost post = new HttpPost(feedUrl);
   post.setHeader(X_HTTP_METHOD_OVERRIDE, "PUT");
   post.setEntity(entity);
   callMethod(post, operation);
 }
 /**
  * Performs a HTTP PUT request, saves an attachment.
  *
  * @return {@link Response}
  */
 Response put(URI uri, InputStream instream, String contentType) {
   HttpResponse response = null;
   try {
     HttpPut httpPut = new HttpPut(uri);
     InputStreamEntity entity = new InputStreamEntity(instream, -1);
     entity.setContentType(contentType);
     httpPut.setEntity(entity);
     response = executeRequest(httpPut);
     return getResponse(response);
   } finally {
     close(response);
   }
 }
Beispiel #6
0
  /**
   * This file will post the flac file to google and store the Json String in jsonResponse data
   * member
   */
  private void postFLAC() {
    try {
      // long start = System.currentTimeMillis();

      // Load the file stream from the given filename
      File file = new File(FLACFileName);

      InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);

      // Set the content type of the request entity to binary octet stream.. Taken from the chunked
      // post example HTTPClient
      reqEntity.setContentType("binary/octet-stream");
      // reqEntity.setChunked(true); // Uncomment this line, but I feel it slows stuff down... Quick
      // Tests show no difference

      // set the POST request entity...
      httppost.setEntity(reqEntity);

      // System.out.println("executing request " + httppost.getRequestLine());

      // Create an httpResponse object and execute the POST
      HttpResponse response = httpclient.execute(httppost);

      // Capture the Entity and get content
      HttpEntity resEntity = response.getEntity();

      // System.out.println(System.currentTimeMillis()-start);

      String buffer;
      jsonResponse = "";

      br = new BufferedReader(new InputStreamReader(resEntity.getContent()));
      while ((buffer = br.readLine()) != null) {
        jsonResponse += buffer;
      }

      // System.out.println("Content: "+jsonResponse);

      // Close Buffered Reader and content stream.
      EntityUtils.consume(resEntity);
      br.close();
    } catch (Exception ee) {
      // In the event this POST Request FAILED
      ee.printStackTrace();
      jsonResponse = "_failed_";
    } finally {
      // Finally shut down the client
      httpclient.getConnectionManager().shutdown();
    }
  }
  public static int addImage(String baseUrl, String imagePlantId, String filePath) {
    File file = new File(filePath);
    try {
      HttpClient client = getClient();

      String url = baseUrl + imagePlantId + "/images";
      HttpPost httppost = new HttpPost(url);
      InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
      reqEntity.setContentType("binary/octet-stream");
      reqEntity.setChunked(true);
      httppost.setEntity(reqEntity);
      HttpResponse response = client.execute(httppost);
      return response.getStatusLine().getStatusCode();
    } catch (Exception e) {
      return -1;
    }
  }
Beispiel #8
0
  private static HttpResponse transformResponse(Response response) {
    int code = response.code();
    String message = response.message();
    BasicHttpResponse httpResponse = new BasicHttpResponse(HTTP_1_1, code, message);

    ResponseBody body = response.body();
    InputStreamEntity entity = new InputStreamEntity(body.byteStream(), body.contentLength());
    httpResponse.setEntity(entity);

    Headers headers = response.headers();
    for (int i = 0; i < headers.size(); i++) {
      String name = headers.name(i);
      String value = headers.value(i);
      httpResponse.addHeader(name, value);
      if ("Content-Type".equalsIgnoreCase(name)) {
        entity.setContentType(value);
      } else if ("Content-Encoding".equalsIgnoreCase(name)) {
        entity.setContentEncoding(value);
      }
    }

    return httpResponse;
  }
 @Test
 public void testIsStatusExpectationFailedAndEntityRepeatable()
     throws UnsupportedEncodingException {
   final SardineHttpClientImpl sardine = new SardineHttpClientImpl(new DefaultHttpClient());
   final HttpResponseException exceptionExpectationFailed =
       new HttpResponseException(HttpStatus.SC_EXPECTATION_FAILED, "Expectation failed");
   final HttpResponseException otherException =
       new HttpResponseException(HttpStatus.SC_CONFLICT, "Conflict");
   final StringEntity repeatableEntity = new StringEntity("hallo");
   final InputStreamEntity nonRepeatableEntity =
       new InputStreamEntity(new ByteArrayInputStream("hallo".getBytes()), -1);
   assertTrue(repeatableEntity.isRepeatable());
   assertFalse(nonRepeatableEntity.isRepeatable());
   assertTrue(
       sardine.isStatusExpectationFailedAndEntityRepeatable(
           exceptionExpectationFailed, repeatableEntity));
   assertFalse(
       sardine.isStatusExpectationFailedAndEntityRepeatable(otherException, repeatableEntity));
   assertFalse(
       sardine.isStatusExpectationFailedAndEntityRepeatable(
           exceptionExpectationFailed, nonRepeatableEntity));
   assertFalse(
       sardine.isStatusExpectationFailedAndEntityRepeatable(otherException, nonRepeatableEntity));
 }
  private Boolean uploadFiles(String mFileName, String mFilePath) {
    webServices = new WebServices();
    jsonParserClass = new JsonParserClass();
    boolean isValid = false;
    byte[] bytes = null;
    String url = "";
    File file = null;
    try {
      url =
          webServices.FILEUPLOAD
              + "/"
              + mFileName; // "http://vsuppliervm.cloudapp.net:5132/FileAttachmentService.svc/FileUpload/";
      file = new File(mFilePath);
    } catch (Exception e) {
      e.printStackTrace();
    }
    try {
      FileInputStream fis = new FileInputStream(file);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] buf = new byte[1024];
      try {
        for (int readNum; (readNum = fis.read(buf)) != -1; ) {
          bos.write(buf, 0, readNum); // no doubt here is 0
          System.out.println("read " + readNum + " bytes,");
        }
      } catch (IOException ex) {
      }
      bytes = bos.toByteArray();

    } catch (Exception e) {
      Log.d("Exception", "Exception");
      e.printStackTrace();
    }
    try {
      ByteArrayInputStream instream = new ByteArrayInputStream(bytes);
      HttpClient httpclient = new DefaultHttpClient();
      url += "/" + bytes.length;
      HttpPost httppost = new HttpPost(url);
      InputStreamEntity reqEntity = new InputStreamEntity(instream, bytes.length);
      httppost.setEntity(reqEntity);
      reqEntity.setContentType("binary/octet-stream");

      httppost.setHeader("Content-type", "application/octet-stream");
      reqEntity.setChunked(true); // Send in multiple parts if needed
      reqEntity.setContentEncoding("utf-8");
      HttpResponse response = httpclient.execute(httppost);
      HttpEntity entity = response.getEntity();
      String result = EntityUtils.toString(entity);

      if (result == null || result.length() == 0) {
        isValid = false;
      } else {
        attachimageUrl = attachimageUrl + "," + jsonParserClass.parseAttachImageUrl(result);
        isValid = true;
      }

      int statusCode = response.getStatusLine().getStatusCode();
      Log.d("statusCode", "" + statusCode);
      if (statusCode != 200) {
        return false;
      }
      isValid = true;
    } catch (Exception e) {
      e.printStackTrace();
      Log.e("Exception in AsyncTask-doInBackgroung", e.toString());
    }
    return isValid;
  }