Ejemplo n.º 1
0
  public static String postFile(
      String host, List<BasicNameValuePair> params, String fileName, String encoding) {
    HttpPost post = new HttpPost(host);
    try {
      File file = new File(fileName);
      MultipartEntity multipart = new MultipartEntity();
      for (BasicNameValuePair pair : params) {
        multipart.addPart(
            pair.getName(), new StringBody(pair.getValue(), Charset.forName(HTTP.UTF_8)));
      }

      multipart.addPart("file", new FileBody(file, "*/*", HTTP.UTF_8));
      HttpClient client = new DefaultHttpClient();
      post.addHeader("charset", encoding);
      post.setEntity(multipart);
      HttpResponse response = client.execute(post);
      String result = "";
      int statusCode = response.getStatusLine().getStatusCode();

      if (statusCode == 200) {
        result = EntityUtils.toString(response.getEntity(), encoding);
      }

      return result;
    } catch (Exception e) {
      Log.e("error", e.getMessage());
      return "";
    }
  }
  @Override
  public boolean userHasRole(String userId, String roleName) throws Exception {
    // Add AuthCache to the execution context
    BasicHttpContext ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost("/api/secure/jsonws/role/has-user-role");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    entity.addPart("userId", new StringBody(userId, Charset.forName("UTF-8")));
    entity.addPart("companyId", new StringBody(companyId, Charset.forName("UTF-8")));
    entity.addPart("name", new StringBody(roleName, Charset.forName("UTF-8")));
    entity.addPart("inherited", new StringBody("false", Charset.forName("UTF-8")));

    post.setEntity(entity);

    HttpResponse resp = httpclient.execute(targetHost, post, ctx);
    System.out.println("userHasRole Status:[" + resp.getStatusLine() + "]");

    String response = null;
    if (resp.getEntity() != null) {
      response = EntityUtils.toString(resp.getEntity());
    }
    System.out.println("userHasRole Res:[" + response + "]");

    JSONDeserializer<Boolean> deserializer = new JSONDeserializer<Boolean>();
    Boolean hasRole = deserializer.deserialize(response, Boolean.class);

    EntityUtils.consume(resp.getEntity());

    return hasRole;
  }
Ejemplo n.º 3
0
  public static String executeMultipartPost(
      String postUrl, Map<String, Object> params, String accessTokens) throws Exception {
    try {
      HttpClient httpClient = theThreadSafeHttpClient();
      HttpPost postRequest = new HttpPost(postUrl);
      postRequest.addHeader("Accept-Charset", HTTP.UTF_8);
      postRequest.addHeader("User-Agent", MOBILE_USER_AGENT);
      postRequest.setHeader("Cache-Control", "max-age=3, must-revalidate, private");
      postRequest.setHeader(
          "Authorization",
          "OAuth oauth_token="
              + accessTokens
              + ", oauth_consumer_key=a324957217164fd1d76b4b60d037abec, oauth_version=1.0, oauth_signature_method=HMAC-SHA1, oauth_timestamp=1322049404, oauth_nonce=-5195915877644743836, oauth_signature=wggOr1ia7juVbG%2FZ2ydImmiC%2Ft4%3D");

      MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
      Set<String> names = params.keySet();
      for (String name : names) {
        Object value = params.get(name);
        if (value instanceof StringBody) {
          reqEntity.addPart(name, (StringBody) value);
        } else if (value instanceof File) {
          reqEntity.addPart("media", new FileBody((File) value));
        }
      }
      postRequest.setEntity(reqEntity);

      HttpResponse response = httpClient.execute(postRequest);
      return EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
    } catch (Exception e) {
      // handle exception here
      e.printStackTrace();
    }
    return "";
  }
Ejemplo n.º 4
0
  @Test
  public void testMultipart() throws IOException, JSONException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + PORT + "/");

    File image = new File("resources/test/base.png");
    FileBody imagePart = new FileBody(image);
    StringBody messagePart = new StringBody("some message");

    MultipartEntity req = new MultipartEntity();
    req.addPart("image", imagePart);
    req.addPart("message", messagePart);
    httppost.setEntity(req);

    ImageEchoServer server = new ImageEchoServer(PORT);
    HttpResponse response = httpclient.execute(httppost);
    server.stop();

    HttpEntity resp = response.getEntity();
    assertThat(resp.getContentType().getValue(), is("application/json"));

    // sweet one-liner to convert an inputstream to a string from stackoverflow:
    // http://stackoverflow.com/questions/309424/in-java-how-do-i-read-convert-an-inputstream-to-a-string
    String out = new Scanner(resp.getContent()).useDelimiter("\\A").next();

    JSONObject json = new JSONObject(out);

    String base64 = Base64.encodeFromFile("resources/test/base.png");

    assertThat(json.getString("screenshot"), is(base64));
    assertThat(json.getBoolean("imageEcho"), is(true));
  }
  public void tstPostImage() throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://10.0.0.2:8080/rs/solve");
    File file = new File("/Users/alexwinston/Desktop/photo.PNG");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/png");
    mpEntity.addPart("image", cbFile);

    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
Ejemplo n.º 6
0
  @Test
  public void testMultiPartIndividualFileToLarge() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {
      String uri = DefaultServer.getDefaultServerURL() + "/servletContext/3";
      HttpPost post = new HttpPost(uri);
      MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

      entity.addPart(
          "formValue", new StringBody("myValue", "text/plain", Charset.forName("UTF-8")));
      entity.addPart(
          "file",
          new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

      post.setEntity(entity);
      HttpResponse result = client.execute(post);
      String response = HttpClientUtils.readResponse(result);
      Assert.assertEquals(
          "TEST FAILED: wrong response code\n" + response,
          500,
          result.getStatusLine().getStatusCode());
    } finally {
      client.getConnectionManager().shutdown();
    }
  }
Ejemplo n.º 7
0
  public boolean sendUploadFile(File file) {
    String url = SENSORMAP_UPLOADFILE_URL;
    if (D) Log.d(TAG, url);

    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);
    request.setHeader("User-Agent", HTTP_USER_AGENT);
    MultipartEntity entity = new MultipartEntity();
    ContentBody contentBody = new FileBody(file);
    FormBodyPart bodyPart = new FormBodyPart("file", contentBody);
    entity.addPart(bodyPart);
    request.setEntity(entity);

    try {
      HttpResponse response = client.execute(request);
      StatusLine status = response.getStatusLine();
      if (status.getStatusCode() == HTTP_STATUS_OK) {
        mLastStatus = Status.SUCCESS;
        return true;
      }
    } catch (ClientProtocolException e) {
      mLastStatus = Status.EXCEPTION;
      e.printStackTrace();
      Log.e(TAG, "Exception in sendUploadFile");
    } catch (IOException e) {
      mLastStatus = Status.EXCEPTION;
      e.printStackTrace();
      Log.e(TAG, "Exception in sendUploadFile");
    }

    return false;
  }
Ejemplo n.º 8
0
  public String uploadService(ArrayList<String> arrlink, TokenDTO token, String description) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(Constants.URL_UPLOAD);

    postRequest.setHeader("Authorization", token.getToken_type() + " " + token.getAccess_token());
    HttpEntity httpEntity = null;
    try {
      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart("Desc", new StringBody(description));
      reqEntity.addPart("CountryCode", new StringBody("1"));

      for (String pathImg : arrlink) {
        reqEntity.addPart("filename", new FileBody(new File(pathImg)));
      }

      postRequest.setEntity(reqEntity);

      HttpResponse response = httpclient.execute(postRequest);
      httpEntity = response.getEntity();
      responsecontent = EntityUtils.toString(httpEntity);

    } catch (Exception e) {
      // TODO: handle exception
    }
    return responsecontent;
  }
  @Test
  public void testFileUpload() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {

      HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
      // post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
      MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

      entity.addPart(
          "formValue", new StringBody("myValue", "text/plain", Charset.forName("UTF-8")));
      entity.addPart(
          "file",
          new FileBody(
              new File(
                  MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

      post.setEntity(entity);
      HttpResponse result = client.execute(post);
      Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
      HttpClientUtils.readResponse(result);

    } finally {
      client.getConnectionManager().shutdown();
    }
  }
  @Override
  public <V> V postUpload(
      String uri,
      Map<String, String> stringParts,
      InputStream in,
      String mimeType,
      String fileName,
      final long fileSize,
      Class<V> type)
      throws IOException {
    HttpPost request = new HttpPost(createURI(uri));
    configureRequest(request);

    MultipartEntity entity = new MultipartEntity();
    for (Map.Entry<String, String> entry : stringParts.entrySet())
      entity.addPart(entry.getKey(), StringBody.create(entry.getValue(), "text/plain", UTF_8));

    entity.addPart(
        "file",
        new InputStreamBody(in, mimeType, fileName) {
          @Override
          public long getContentLength() {
            return fileSize;
          }
        });
    request.setEntity(entity);
    return executeRequest(request, type, null);
  }
Ejemplo n.º 11
0
 public HttpEntity getResponse(String uri, FileBody fileBody, StringBody stringBody) {
   HttpClient httpclient = new DefaultHttpClient();
   HttpEntity resEntity = null;
   try {
     HttpPost httppost = new HttpPost("http://192.168.67.75:8080" + uri);
     MultipartEntity reqEntity = new MultipartEntity();
     reqEntity.addPart("fileBody", fileBody);
     reqEntity.addPart("stringBody", stringBody);
     httppost.setEntity(reqEntity);
     System.out.println("executing request " + httppost.getRequestLine());
     HttpResponse response = httpclient.execute(httppost);
     resEntity = response.getEntity();
     return resEntity;
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (ClientProtocolException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       httpclient.getConnectionManager().shutdown();
     } catch (Exception ignore) {
       System.out.println("error");
     }
   }
   return null;
 }
  public Object updateApplication(String appName, String absolutePath, IProgressMonitor monitor)
      throws APIException {
    try {
      final File file = new File(absolutePath);
      final FileBody fileBody = new FileBody(file);

      final MultipartEntity entity = new MultipartEntity();
      entity.addPart(file.getName(), fileBody);

      final HttpPut httpPut = new HttpPut();
      httpPut.setEntity(entity);

      Object response = httpJSONAPI(httpPut, getUpdateURI(appName));

      if (response instanceof JSONObject) {
        JSONObject json = (JSONObject) response;

        if (isSuccess(json)) {
          System.out.println("updateApplication: success."); // $NON-NLS-1$
        } else {
          return "updateApplication: error " + getUpdateURI(appName); // $NON-NLS-1$
        }
      }

      httpPut.releaseConnection();
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    return null;
  }
  public Object installApplication(String absolutePath, String appName, IProgressMonitor submon)
      throws APIException {
    try {
      FileBody fileBody = new FileBody(new File(absolutePath));

      MultipartEntity entity = new MultipartEntity();
      entity.addPart("deployWar", fileBody); // $NON-NLS-1$

      HttpPost httpPost = new HttpPost();
      httpPost.setEntity(entity);

      Object response = httpJSONAPI(httpPost, getDeployURI(appName));

      if (response instanceof JSONObject) {
        JSONObject json = (JSONObject) response;

        if (isSuccess(json)) {
          System.out.println("installApplication: Sucess.\n\n"); // $NON-NLS-1$
        } else {
          if (isError(json)) {
            return json.getString("error"); // $NON-NLS-1$
          } else {
            return "installApplication error " + getDeployURI(appName); // $NON-NLS-1$
          }
        }
      }

      httpPost.releaseConnection();
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    return null;
  }
  @Override
  public List<Role> getUserRoles(String userId) throws Exception {
    // Add AuthCache to the execution context
    BasicHttpContext ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost("/api/secure/jsonws/role/get-user-roles");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    entity.addPart("userId", new StringBody(userId, Charset.forName("UTF-8")));

    post.setEntity(entity);

    HttpResponse resp = httpclient.execute(targetHost, post, ctx);
    System.out.println("getOrganizationsByUserId Status:[" + resp.getStatusLine() + "]");

    String response = null;
    if (resp.getEntity() != null) {
      response = EntityUtils.toString(resp.getEntity());
    }
    System.out.println("getUserRoles Res:[" + response + "]");

    ArrayList<Role> roles =
        new JSONDeserializer<ArrayList<Role>>().use("values", Role.class).deserialize(response);

    EntityUtils.consume(resp.getEntity());

    return roles;
  }
  private void send(String content, String slotStartDate, String slotEndDate) {
    String url = obdProperties.getMessageDeliveryBaseUrl();
    logger.info(String.format("Uploading the campaign messages to url: %s", url));
    logger.debug(String.format("Uploading campaign messages content : %s", content));

    String fileName = obdProperties.getMessageDeliveryFileName();
    String file = obdProperties.getMessageDeliveryFile();

    HttpPost httpPost = new HttpPost(url);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart(file, new ByteArrayBody(content.getBytes(), "text/plain", fileName));

    try {
      reqEntity.addPart(START_DATE_PARAM_NAME, new StringBody(slotStartDate));
      reqEntity.addPart(END_DATE_PARAM_NAME, new StringBody(slotEndDate));
      logRequest(url, slotStartDate, slotEndDate);

      httpPost.setEntity(reqEntity);

      HttpResponse response = obdHttpClient.execute(httpPost);
      String responseContent =
          readResponse(
              response); // Read the response from stream first thing. As it should be read
                         // completely before making any other request.
      validateResponse(response, responseContent);
      logger.info(
          String.format(
              "Uploaded campaign messages successfully.\nResponse:\n%s", responseContent));
    } catch (IOException ex) {
      logger.error("Sending messages to OBD failed", ex);
      throw new RuntimeException(ex);
    }
  }
  /**
   * Classifies the images against the label groups and labels. The response includes a score for a
   * label if the score meets the minimum threshold of 0.5. If no score meets the threshold for an
   * image, no labels are returned.
   *
   * @param image the file image
   * @param labelSet the labels to classify against
   * @return the visual recognition images
   */
  public RecognizedImage recognize(final File image, final LabelSet labelSet) {
    if (image == null) throw new IllegalArgumentException("image can not be null");
    try {

      Request request = Request.Post("/v1/tag/recognize");

      MultipartEntity reqEntity = new MultipartEntity();

      // Set the image_file
      FileBody bin = new FileBody(image);
      reqEntity.addPart(IMG_FILE, bin);

      if (labelSet != null) {
        StringBody labels =
            new StringBody(GsonSingleton.getGson().toJson(labelSet), Charset.forName("UTF-8"));

        // Set the labels_to_check
        reqEntity.addPart(LABELS_TO_CHECK, labels);
      }
      request.withEntity(reqEntity);

      HttpResponse response = execute(request.build());
      String resultJson = ResponseUtil.getString(response);
      VisualRecognitionImages recognizedImages =
          GsonSingleton.getGson().fromJson(resultJson, VisualRecognitionImages.class);
      return recognizedImages.getImages().get(0);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  @Override
  protected Boolean doInBackground(File... params) {
    String server = BuildConfig.API_BASE_URL;
    ICredentials credentials = new UserCredentials(mContext);
    String url = server + "/api/nodes/" + wmID + "/photos?api_key=" + credentials.getApiKey();
    Log.d(TAG, url);

    File image = params[0];

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    try {
      MultipartEntity entity = new MultipartEntity();
      entity.addPart("photo", new FileBody(image));
      httppost.setEntity(entity);
      HttpResponse response = httpclient.execute(httppost);
      String result = EntityUtils.toString(response.getEntity());
      Log.d(TAG, result + "");
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      Log.d(TAG, e.getLocalizedMessage());
      return false;
    }
  }
Ejemplo n.º 18
0
  private void fileUpload() throws Exception {
    httpPost = new NUHttpPost(uploadURL);

    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    mpEntity.addPart("akey", new StringBody(fileCloudAccount.getFileCloudAPIKey()));

    mpEntity.addPart("Filedata", createMonitoredFileBody());
    httpPost.setEntity(mpEntity);
    NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPost.getRequestLine());
    NULogger.getLogger().info("Now uploading your file into filecloud.io .....");
    uploading();
    httpResponse = httpclient.execute(httpPost);
    HttpEntity resEntity = httpResponse.getEntity();
    NULogger.getLogger().info(httpResponse.getStatusLine().toString());
    if (resEntity != null) {
      stringResponse = EntityUtils.toString(resEntity);
    }

    // Get JSONObject
    jSonObject = new JSONObject(stringResponse);
    String responseStatus = jSonObject.getString("status");

    if (!"ok".equals(responseStatus)) {
      // Handle errors
      throw new Exception("Error: " + jSonObject.getString("message"));
    }

    String downloadURL = "http://filecloud.io/" + jSonObject.getString("ukey");
    NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadURL);
    downURL = downloadURL;

    status = UploadStatus.UPLOADFINISHED;
  }
Ejemplo n.º 19
0
 public String addVideo(String json, InputStream is, String fileName)
     throws ClientProtocolException, IOException {
   HttpClient httpclient = getHttpClient();
   try {
     File video = new File(fileName);
     OutputStream out = new FileOutputStream(video);
     IOUtils.copy(is, out);
     httpclient
         .getParams()
         .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
     HttpPost post = new HttpPost(BC_MEDIA_URL);
     MultipartEntity multipart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
     ContentBody content =
         new FileBody(video, new MimetypesFileTypeMap().getContentType(fileName));
     multipart.addPart("JSON-RPC", new StringBody(json));
     multipart.addPart("file", content);
     post.setEntity(multipart);
     HttpResponse response = httpclient.execute(post);
     HttpEntity entity = response.getEntity();
     if (entity != null) {
       String result = EntityUtils.toString(entity);
       return result;
     }
   } finally {
     httpclient.getConnectionManager().shutdown();
   }
   return "";
 }
Ejemplo n.º 20
0
  public static void post(String url, String filepath, String desp, UploadListener listner)
      throws UnsupportedEncodingException {
    listner.onUploadBegin();
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);
    FileBody file = new FileBody(new File(filepath));
    StringBody descript = new StringBody(desp);

    MultipartEntity reqEntity = new CountMultipartEntity(listner);
    reqEntity.addPart("file", file);
    reqEntity.addPart("path", descript);
    httppost.setEntity(reqEntity);
    try {
      HttpResponse response = httpclient.execute(httppost);
      if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
          System.out.println(EntityUtils.toString(entity));
        }
        if (entity != null) {
          entity.consumeContent();
        }
      }
    } catch (Exception e) {
      listner.onUploadFinish();
      e.printStackTrace();
      Log.e(TAG, "exception", e.getCause());
    }
    listner.onUploadFinish();
  }
  private void fileupload() throws Exception {

    if (!solidfilesAccount.loginsuccessful) {
      NUHttpClientUtils.getData("http://www.solidfiles.com/", httpContext);
    }

    httpPost = new NUHttpPost("http://www.solidfiles.com/upload/process/0/");

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("name", new StringBody(file.getName()));
    reqEntity.addPart("file", createMonitoredFileBody());

    httpPost.setEntity(reqEntity);
    uploading();
    NULogger.getLogger().info("Now uploading your file into solidfiles.com. Please wait...");
    httpResponse = httpclient.execute(httpPost, httpContext);
    HttpEntity resEntity = httpResponse.getEntity();

    String downloadCode;
    if (resEntity != null) {
      gettingLink();
      downloadCode = EntityUtils.toString(resEntity);
      NULogger.getLogger().log(Level.INFO, "Download code :{0}", downloadCode);
      downloadlink = String.format(downloadlink, downloadCode);
    }

    downURL = downloadlink;
    uploadFinished();
  }
Ejemplo n.º 22
0
  public static boolean uploadFile(
      String url, String uploadKey, File file, Map<String, String> params) {
    // TODO httpClient连接关闭问题需要考虑
    try {
      HttpPost httppost = new HttpPost("http://www.new_magic.com/service.php");

      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart(uploadKey, new FileBody(file));
      for (Map.Entry<String, String> entry : params.entrySet()) {
        StringBody value = new StringBody(entry.getValue());
        reqEntity.addPart(entry.getKey(), value);
      }

      httppost.setEntity(reqEntity);
      HttpResponse response = httpClient.execute(httppost);
      int statusCode = response.getStatusLine().getStatusCode();

      if (statusCode == HttpStatus.SC_OK) {
        HttpEntity resEntity = response.getEntity();
        String body = EntityUtils.toString(resEntity);
        EntityUtils.consume(resEntity);

        Map<String, Object> responseMap = JsonUtil.parseJson(body, Map.class);
        if (responseMap.containsKey("code") && responseMap.get("code").equals(10000)) {
          return true;
        }
      }
    } catch (Exception e) {
      log.error("", e);
    }
    return false;
  }
Ejemplo n.º 23
0
  final <T extends ServerResponse> T doPost(CommandArguments args, Class<T> clazz, String url)
      throws FlickrException {
    try {
      OAuthRequest request = new OAuthRequest(Verb.POST, url);

      // check for proxy, use if available
      if (proxy != null) {
        request.setProxy(proxy);
      }

      for (Map.Entry<String, Object> param : args.getParameters().entrySet()) {
        if (param.getValue() instanceof String) {
          request.addQuerystringParameter(param.getKey(), (String) param.getValue());
        }
      }

      oauth.signRequest(request);

      MultipartEntity multipart = args.getBody(request.getOauthParameters());
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      multipart.writeTo(baos);

      request.addPayload(baos.toByteArray());
      request.addHeader("Content-type", multipart.getContentType().getValue());

      Response response = request.send();
      String body = response.getBody();

      return parseBody(args, clazz, body);

    } catch (IOException ex) {
      throw new UnsupportedOperationException("Error preparing multipart request", ex);
    }
  }
Ejemplo n.º 24
0
  private void PostData(String url, String mac, String texto)
      throws ClientProtocolException, IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    MultipartEntity form = new MultipartEntity();
    byte[] test = {0x55, 0x23, 0x33};
    form.addPart("mac", new StringBody(mac));
    form.addPart("datos", new StringBody(texto));
    // form.addPart("datos", new IntArrayBody(data, null));

    httppost.setEntity(form);

    // Execute and get the response.
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();

    if (entity != null) {
      InputStream instream = entity.getContent();
      try {
        // do something useful
      } finally {
        instream.close();
      }
    }
  }
Ejemplo n.º 25
0
  Uploadsim(String pathu, String type) {
    try {
      HttpClient httpclient = new DefaultHttpClient();
      URI url = new URI("http://uploads.im/api?format=xml");
      HttpPost httppost = new HttpPost(url);
      FileBody bin = new FileBody(new File(pathu));
      MultipartEntity reqEntity = new MultipartEntity();
      reqEntity.addPart("image", bin);
      httppost.setEntity(reqEntity);
      HttpResponse response = httpclient.execute(httppost);
      HttpEntity responseEntity = response.getEntity();
      String answer;
      if (responseEntity != null) {
        answer = EntityUtils.toString(responseEntity);
        getLink(answer, type, pathu);
      } else {
        if (net.makeshot.settings.Static.tooltip == 1)
          Notifications.showNotification(false, "ops :(", pathu);
        if (net.makeshot.settings.Static.playSound == 1) Play.error();
      }

    } catch (URISyntaxException | ParseException | IOException e) {
      if (net.makeshot.settings.Static.tooltip == 1)
        Notifications.showNotification(false, "ops :(", pathu);
      if (net.makeshot.settings.Static.playSound == 1) Play.error();
      LOG.error(e);
    }
  }
Ejemplo n.º 26
0
 /**
  * Envoie une photo vers la plateforme web
  *
  * @param filename Nom de la photo à envoyer
  */
 void envoiPhoto(String filename) {
   String TAG = "envoiPhoto";
   Log.i(TAG, "Envoie de la photo");
   File pictureFile = new File(filename); // On récupère le fichier image
   // Initialisation du client HTTP
   HttpClient httpClient = new DefaultHttpClient();
   httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
   /* Création de la requête POST. On lui donne en adresse l'adresse du serveur
   suivi de /upload. Le serveur mis en place pendant le projet attend
   une requête de ce type */
   HttpPost postRequest = new HttpPost("http://192.168.43.8:9001/upload");
   try {
     // Création de l'entité qui sera associée à la requête
     MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
     // On lui ajoute les champs "picture" et "email"
     // !!Attention, les noms "picture" et "email" ont leur importance, c'est ce
     // qu'attend le serveur
     entity.addPart("picture", new FileBody(((File) pictureFile), "image/jpeg"));
     entity.addPart(
         "email",
         new StringBody("*****@*****.**", "text/plain", Charset.forName("UTF-8")));
     postRequest.setEntity(entity); // Exécution de la requête
     String response = EntityUtils.toString(httpClient.execute(postRequest).getEntity(), "UTF-8");
     Log.i(TAG, "Requete exécutée");
   } catch (IOException e) {
     Log.i(TAG, "L'exécution de la requête lance une exception car : " + e.toString());
   }
   Log.i(TAG, "Sortie envoiPhoto");
 }
Ejemplo n.º 27
0
  public void uploadFile(String url, File file, RemoteUploaderResponseListener handler)
      throws ParseException, ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();

    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(10000));
    httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    HttpPost request = new HttpPost(url);

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);

    entity.addPart(
        "Filename", new StringBody(file.getName(), "text/plain", Charset.forName("UTF-8")));
    entity.addPart("Filedata", new FileBody((file), "application/octet-stream"));
    entity.addPart(
        "Upload", new StringBody("Submit Query", "text/plain", Charset.forName("UTF-8")));
    request.setEntity(entity);

    String response = EntityUtils.toString(httpclient.execute(request).getEntity(), "UTF-8");

    handler.uploaded(file.getName(), file.length(), response);

    httpclient.getConnectionManager().shutdown();
  }
  public User updateUserDetails(String username, String displayName, String bio, MediaFile image)
      throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/user/" + username);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    if (displayName != null) {
      addStringPart(entity, "displayName", displayName);
    }
    if (bio != null) {
      addStringPart(entity, "bio", bio);
    }
    if (image != null) {
      entity.addPart("image", new ByteArrayBody(image.getData(), image.getFilename()));
    }

    request.addHeader("Content-Type", entity.getContentType().getValue());
    addMultipartEntity(request, entity);
    oauthSignRequest(request);

    Response response = request.send();

    final String repsonseBody = response.getBody();
    if (response.getCode() == 200) {
      return new UserParser().parseUserProfile(repsonseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
  public Noticeboard editNoticeboard(
      String domain,
      String name,
      String description,
      Boolean moderated,
      Boolean featured,
      MediaFile cover)
      throws N0ticeException {
    OAuthRequest request = createOauthRequest(Verb.POST, urlBuilder.noticeBoard(domain));
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    addEntityPartParameter(entity, "name", name);
    addEntityPartParameter(entity, "description", description);
    addEntityPartParameter(
        entity, "moderated", moderated != null ? Boolean.toString(moderated) : null);
    addEntityPartParameter(
        entity, "featured", featured != null ? Boolean.toString(featured) : null);
    if (cover != null) {
      entity.addPart("cover", new ByteArrayBody(cover.getData(), cover.getFilename()));
    }

    // TODO implement
    /*
    if (endDate != null) {
    	addEntityPartParameter(entity, "endDate", ISODateTimeFormat.dateTimeNoMillis().print(new DateTime(endDate)));
    }
    if (cover != null) {
    	entity.addPart("cover", new ByteArrayBody(cover.getData(), cover.getFilename()));
    }

    StringBuilder supportedMediaTypesValue = new StringBuilder();
    Iterator<MediaType> supportedMediaTypesIterator = supportedMediaTypes.iterator();
    while(supportedMediaTypesIterator.hasNext()) {
    	supportedMediaTypesValue.append(supportedMediaTypesIterator.next());
    	if (supportedMediaTypesIterator.hasNext()) {
    		supportedMediaTypesValue.append(COMMA);
    	}
    }
    addEntityPartParameter(entity, "supportedMediaTypes", supportedMediaTypesValue.toString());

    if (group != null) {
    	addEntityPartParameter(entity, "group", group);
    }
    */

    request.addHeader("Content-Type", entity.getContentType().getValue());
    addMultipartEntity(request, entity);
    oauthSignRequest(request);

    Response response = request.send();

    final String responseBody = response.getBody();
    if (response.getCode() == 200) {
      return noticeboardParser.parseNoticeboardResult(responseBody);
    }

    handleExceptions(response);
    throw new N0ticeException(response.getBody());
  }
Ejemplo n.º 30
0
 /**
  * Adds necessary address fields to a multipart request entity.
  *
  * @param reqEntity The multipart request entity to add fields to.
  * @throws UnsupportedEncodingException
  */
 public void addAddress(MultipartEntity reqEntity) throws UnsupportedEncodingException {
   reqEntity.addPart("street1", new StringBody(street1()));
   reqEntity.addPart("street2", new StringBody(street2()));
   reqEntity.addPart("city", new StringBody(this._random.makeCString(4, 14)));
   reqEntity.addPart("state", new StringBody(this._random.makeCString(2, 2).toUpperCase()));
   reqEntity.addPart("zip", new StringBody(this._random.makeNString(5, 5)));
   reqEntity.addPart("country", new StringBody(country()));
 }