Beispiel #1
0
  /**
   * Sends a POST request with a file and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param file The file to upload
   * @param responseClass The class to deserialise the Json response to. Can be null if no response
   *     message is expected.
   * @param fields Any name-value pairs to serialise
   * @param <T> The type to deserialise the response to.
   * @return A {@link Response} containing the deserialised body, if any.
   * @throws IOException If an error occurs.
   * @see MultipartEntityBuilder
   */
  public <T> Response<T> post(
      Endpoint endpoint, File file, Class<T> responseClass, NameValuePair... fields)
      throws IOException {
    if (file == null) {
      return post(endpoint, responseClass, fields);
    } // deal with null case

    // Create the request
    HttpPost post = new HttpPost(endpoint.url());
    post.setHeaders(combineHeaders());

    // Add fields as text pairs
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    for (NameValuePair field : fields) {
      multipartEntityBuilder.addTextBody(field.getName(), field.getValue());
    }
    // Add file as binary
    FileBody bin = new FileBody(file);
    multipartEntityBuilder.addPart("file", bin);

    // Set the body
    post.setEntity(multipartEntityBuilder.build());

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(post)) {
      T body = deserialiseResponseMessage(response, responseClass);
      return new Response<>(response.getStatusLine(), body);
    }
  }
  /**
   * register to the server
   *
   * @param context Activity or Service context
   * @param regId gcmId registered from Google
   */
  public static boolean register(Context context, String regId) {

    String serverUrl = ServerUrl.SERVER_URL_GCM_REGISTER();
    String uid = PreferenceControl.getUID();

    try {
      DefaultHttpClient httpClient = HttpSecureClientGenerator.getSecureHttpClient();
      HttpPost httpPost = new HttpPost(serverUrl);
      httpClient
          .getParams()
          .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
      builder.addTextBody("uid", uid);
      builder.addTextBody("regId", regId);

      httpPost.setEntity(builder.build());
      boolean result = uploader(httpClient, httpPost);
      GCMRegistrar.setRegisteredOnServer(context, result);
      return result;
    } catch (Exception e) {
      GCMRegistrar.setRegisteredOnServer(context, false);
      return false;
    }
  }
Beispiel #3
0
  /**
   * Sends a POST request with a file and returns the response.
   *
   * @param endpoint The endpoint to send the request to.
   * @param file The file to upload
   * @param responseClass The class to deserialise the Json response to. Can be null if no response
   *     message is expected.
   * @param <T> The type to deserialise the response to.
   * @return A {@link Response} containing the deserialised body, if any.
   * @throws IOException If an error occurs.
   * @see MultipartEntityBuilder
   */
  private <T> Response<T> post(Endpoint endpoint, File file, Class<T> responseClass)
      throws IOException {
    if (file == null) {
      return post(endpoint, responseClass);
    } // deal with null case

    // Create the request
    HttpPost post = new HttpPost(endpoint.url());
    post.setHeaders(combineHeaders());

    // Add fields as text pairs
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    // Add file as binary
    FileBody fileBody = new FileBody(file);
    multipartEntityBuilder.addPart("file", fileBody);

    // Set the body
    post.setEntity(multipartEntityBuilder.build());

    // Send the request and process the response
    try (CloseableHttpResponse response = httpClient().execute(post)) {
      if (String.class.isAssignableFrom(responseClass)) {
        String body = getResponseString(response);
        return new Response(response.getStatusLine(), body);
      } else {
        T body = deserialiseResponseMessage(response, responseClass);
        return new Response<>(response.getStatusLine(), body);
      }
    }
  }
Beispiel #4
0
 @Override
 protected String doInBackground(Void... params) {
   HttpResponse response = null;
   File file = myIncident.getPhoto();
   if (!file.exists()) {
     return "broken";
   }
   FileBody fb = new FileBody(file);
   HttpClient client = new DefaultHttpClient();
   HttpPost post = new HttpPost("http://pittsburgh311.stevenbauer.net/create_report.php");
   MultipartEntityBuilder builder =
       MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
   builder.addPart("file_contents", fb);
   builder.addTextBody("address", myIncident.getAddress());
   builder.addTextBody("email", userProfile.getEmail(getApplicationContext()));
   builder.addTextBody("comment", myIncident.getComment());
   builder.addTextBody("lat", myIncident.getLat());
   builder.addTextBody("lon", myIncident.getLon());
   builder.addTextBody("status", "Open");
   builder.addTextBody("category", myIncident.getCategory());
   builder.addTextBody("photo", file.getName());
   final HttpEntity yourEntity = builder.build();
   post.setEntity(yourEntity);
   try {
     response = client.execute(post);
     return getContent(response);
   } catch (IOException e) {
     e.printStackTrace();
   }
   return null;
 }
 @Test
 public void testMultipartPostWithoutParameters() throws Exception {
   HttpPost post =
       new HttpPost(
           "http://localhost:"
               + PORT_PATH
               + "/rest/customerservice/customers/multipart/withoutParameters");
   MultipartEntityBuilder builder =
       MultipartEntityBuilder.create().setMode(HttpMultipartMode.STRICT);
   builder.addBinaryBody(
       "part1",
       new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()),
       ContentType.create("image/jpeg"),
       "java.jpg");
   builder.addBinaryBody(
       "part2",
       new File(this.getClass().getClassLoader().getResource("java.jpg").toURI()),
       ContentType.create("image/jpeg"),
       "java.jpg");
   StringWriter sw = new StringWriter();
   jaxb.createMarshaller().marshal(new Customer(123, "Raul"), sw);
   builder.addTextBody("body", sw.toString(), ContentType.create("text/xml", Consts.UTF_8));
   post.setEntity(builder.build());
   HttpResponse response = httpclient.execute(post);
   assertEquals(200, response.getStatusLine().getStatusCode());
 }
  /**
   * Get a list of probe requests for a map ID
   *
   * @param mapId Map ID
   * @param dataSince ISO-formatted date string to get probes sent to cloud after date
   * @return List<ProbeRequest>
   */
  public List<ProbeRequest> probesGet(Integer mapId, String dataSince) throws ApiExceptionAndroid {
    Object localVarPostBody = null;

    // verify the required parameter 'mapId' is set
    if (mapId == null) {
      throw new ApiExceptionAndroid(
          400,
          "Missing the required parameter 'mapId' when calling controllersDefaultControllerProbesGet");
    }

    // create path and map variables
    String localVarPath = "/probes".replaceAll("\\{format\\}", "json");

    // query params
    List<PairAndroid> localVarQueryParams = new ArrayList<PairAndroid>();
    // header params
    Map<String, String> localVarHeaderParams = new HashMap<String, String>();
    // form params
    Map<String, String> localVarFormParams = new HashMap<String, String>();

    localVarQueryParams.addAll(ApiInvokerAndroid.parameterToPairs("", "map_id", mapId));

    localVarQueryParams.addAll(ApiInvokerAndroid.parameterToPairs("", "data_since", dataSince));

    String[] localVarContentTypes = {};

    String localVarContentType =
        localVarContentTypes.length > 0 ? localVarContentTypes[0] : "application/json";

    if (localVarContentType.startsWith("multipart/form-data")) {
      // file uploading
      MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create();

      localVarPostBody = localVarBuilder.build();
    } else {
      // normal form params

    }

    try {
      String localVarResponse =
          apiInvoker.invokeAPI(
              basePath,
              localVarPath,
              "GET",
              localVarQueryParams,
              localVarPostBody,
              localVarHeaderParams,
              localVarFormParams,
              localVarContentType);
      if (localVarResponse != null) {
        return (List<ProbeRequest>)
            ApiInvokerAndroid.deserialize(localVarResponse, "array", ProbeRequest.class);
      } else {
        return null;
      }
    } catch (ApiExceptionAndroid ex) {
      throw ex;
    }
  }
  protected HttpPost setupPostWithFileName(HttpPost request, String fileName) {
    if (fileName == null || fileName.length() == 0) return request;

    ContentBody fileBody = new FileBody(new File(fileName), ContentType.DEFAULT_BINARY);

    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    multipartEntity
        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
        .setBoundary("boundaryABC--WebKitFormBoundaryGMApUciYGfDuPa49");
    multipartEntity.addPart("file", fileBody);
    request.setEntity(multipartEntity.build());

    //    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
    // "boundaryABC--WebKitFormBoundaryGMApUciYGfDuPa49", Charset.forName("UTF-8"));
    //    mpEntity.addPart("userfile", fileBody);
    //    request.setEntity(mpEntity);

    //    FileEntity entity = new FileEntity(new File(fileName),
    // ContentType.APPLICATION_OCTET_STREAM);
    //    BasicHeader basicHeader = new BasicHeader(HTTP.CONTENT_TYPE,"application/json");
    // request.getParams().setBooleanParameter("http.protocol.expect-continue", false);
    //    entity.setContentType(basicHeader);

    //    request.setEntity(mpEntity);

    return request;
  }
  /*.................................................................................................................*/
  public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("composeRAxMLCommand")) {

      MultipartEntityBuilder arguments = MultipartEntityBuilder.create();
      StringBuffer sb = new StringBuffer();
      getArguments(
          arguments,
          sb,
          "fileName",
          proteinModelField.getText(),
          dnaModelField.getText(),
          otherOptionsField.getText(),
          bootStrapRepsField.getValue(),
          bootstrapSeed,
          numRunsField.getValue(),
          outgroupTaxSetString,
          null,
          false);
      String command = externalProcRunner.getExecutableCommand() + arguments.toString();
      commandLabel.setText("This command will be used by CIPRes to run RAxML:");
      commandField.setText(command);
    } else if (e.getActionCommand().equalsIgnoreCase("clearCommand")) {
      commandField.setText("");
      commandLabel.setText("");
    }
  }
 public static String uploadMaterial(
     String url, Map<String, String> params, String formDataName, File file) {
   client = getHttpClientInstance();
   URI uri = generateURLParams(url, params);
   HttpPost post = new HttpPost(uri);
   post.setConfig(requestConfig);
   ContentBody contentBody = new FileBody(file);
   HttpEntity reqestEntity =
       MultipartEntityBuilder.create().addPart(formDataName, contentBody).build();
   post.setEntity(reqestEntity);
   String responseStr = null;
   CloseableHttpResponse httpResponse = null;
   try {
     httpResponse = client.execute(post);
     responseStr = generateHttpResponse(httpResponse);
   } catch (IOException e) {
   } finally {
     if (null != httpResponse) {
       try {
         httpResponse.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return responseStr;
 }
Beispiel #10
0
  /**
   * Post方法传送消息
   *
   * @param url 连接的URL
   * @param queryString 请求参数串
   * @return 服务器返回的信息
   * @throws Exception
   */
  public String httpPostWithFile(String url, String queryString, List<NameValuePair> files)
      throws Exception {
    String responseData = null;
    URI tmpUri = new URI(url);
    URI uri =
        new URI(
            tmpUri.getScheme(),
            null,
            tmpUri.getHost(),
            tmpUri.getPort(),
            tmpUri.getPath(),
            queryString,
            null);
    log.info("QHttpClient httpPostWithFile [1]  uri = " + uri.toURL());
    MultipartEntityBuilder mpEntityBuilder = MultipartEntityBuilder.create();
    HttpPost httpPost = new HttpPost(uri);
    StringBody stringBody;
    FileBody fileBody;
    File targetFile;
    String filePath;
    ContentType contentType = ContentType.create("text/plain", "UTF-8");

    List<NameValuePair> queryParamList = QStrOperate.getQueryParamsList(queryString);
    for (NameValuePair queryParam : queryParamList) {
      stringBody = new StringBody(queryParam.getValue(), contentType);
      mpEntityBuilder.addPart(queryParam.getName(), stringBody);
      // log.info("------- "+queryParam.getName()+" = "+queryParam.getValue());
    }

    for (NameValuePair param : files) {
      filePath = param.getValue();
      targetFile = new File(filePath);
      log.info(
          "---------- File Path = "
              + filePath
              + "\n---------------- MIME Types = "
              + QHttpUtil.getContentType(targetFile));
      fileBody =
          new FileBody(
              targetFile, ContentType.create(QHttpUtil.getContentType(targetFile), "UTF-8"));
      mpEntityBuilder.addPart(param.getName(), fileBody);
    }
    // log.info("---------- Entity Content Type = "+mpEntity.getContentType());
    httpPost.setEntity(mpEntityBuilder.build());
    try {
      HttpResponse response = httpClient.execute(httpPost);
      log.info("QHttpClient httpPostWithFile [2] StatusLine = " + response.getStatusLine());
      responseData = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      httpPost.abort();
    }
    log.info("QHttpClient httpPostWithFile [3] responseData = " + responseData);
    return responseData;
  }
 public CoverallsResponse submit(final File file) throws ProcessingException, IOException {
   HttpEntity entity =
       MultipartEntityBuilder.create()
           .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
           .addBinaryBody("json_file", file, MIME_TYPE, FILE_NAME)
           .build();
   HttpPost post = new HttpPost(coverallsUrl);
   post.setEntity(entity);
   HttpResponse response = httpClient.execute(post);
   return parseResponse(response);
 }
Beispiel #12
0
    @Override
    protected String doInBackground(String... url) {

      String resp = "";
      String username = "";

      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLSEC);
      HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLSEC);
      HttpPost request = new HttpPost(url[0]);

      MultipartEntityBuilder MEB = MultipartEntityBuilder.create();
      Charset chars = Charset.forName("UTF-8");
      MEB.setCharset(chars);
      MEB.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
      try {

        JSONArray contactsArray = new JSONArray();

        for (int i = 0; i < selectedItemList.size(); i++) {
          JSONObject contactObj = new JSONObject();
          File getFile = new File(context.getFilesDir().getPath() + "/", selectedItemList.get(i));
          FileBody fb = new FileBody(getFile);
          contactObj.put("contact", selectedItemList.get(i));
          contactsArray.put(contactObj);
          MEB.addPart(selectedItemList.get(i), fb);
          fb = null;
        }

        selectedItemList.clear();
        byte[] contacts = contactsArray.toString().getBytes();
        MEB.addBinaryBody("contactsArray", contacts);
        contactsArray = null;

        HttpEntity ent = MEB.build();
        request.setEntity(ent);
        // request.setEntity(new ByteArrayEntity(file.toString().getBytes("UTF8")));
        MyHttpClient Client = LogonClass.Client;
        Client.putContext(context);
        HttpResponse response = Client.execute(request);
        contactsArray = null;
        resp = EntityUtils.toString(response.getEntity());
      } catch (Exception e) {
        e.printStackTrace();

        resp = "none is righteous";
      }
      Log.e(TAG, "response is " + resp);
      return resp;
    }
  static void getAuthCode() {
    access_token = null;
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("/home/sead/refresh.txt").delete();

    if (gProps == null) {
      initGProps();
    }

    // Contact google for a user code
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {

      String codeUri = gProps.auth_uri.substring(0, gProps.auth_uri.length() - 4) + "device/code";

      HttpPost codeRequest = new HttpPost(codeUri);

      MultipartEntityBuilder meb = MultipartEntityBuilder.create();
      meb.addTextBody("client_id", gProps.client_id);
      meb.addTextBody("scope", "email profile");
      HttpEntity reqEntity = meb.build();

      codeRequest.setEntity(reqEntity);
      CloseableHttpResponse response = httpclient.execute(codeRequest);
      try {

        if (response.getStatusLine().getStatusCode() == 200) {
          HttpEntity resEntity = response.getEntity();
          if (resEntity != null) {
            String responseJSON = EntityUtils.toString(resEntity);
            ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
            device_code = root.get("device_code").asText();
            user_code = root.get("user_code").asText();
            verification_url = root.get("verification_url").asText();
            expires_in = root.get("expires_in").asInt();
          }
        } else {
          log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
        }
      } finally {
        response.close();
        httpclient.close();
      }
    } catch (IOException e) {
      log.error("Error reading sead-google.json or making http requests for code.");
      log.error(e.getMessage());
    }
  }
  private MultipartEntityBuilder _getMultipartEntityBuilder(Map<String, Object> parameters) {

    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    for (Map.Entry<String, Object> entry : parameters.entrySet()) {
      if (_ignoredParameterKeys.contains(entry.getKey())) {
        continue;
      }

      multipartEntityBuilder.addPart(entry.getKey(), _getStringBody(entry.getValue()));
    }

    return multipartEntityBuilder;
  }
  /*.................................................................................................................*/
  public boolean sendJobToCipres(
      MultipartEntityBuilder builder, String tool, MesquiteString jobURL) {
    if (checkUsernamePassword(true)) {
      HttpClient httpclient = getHttpClient();

      if (builder == null) builder = MultipartEntityBuilder.create();
      prepareBuilder(builder, tool, "ZEPHYR.GI." + username + "." + jobNumber);
      jobNumber++;
      ownerModule.storePreferences();

      return postJob(httpclient, builder, jobURL);
    }
    return false;
  }
  protected String upload(String path, Map<String, String> params, Map<String, String> files)
      throws IOException, ClientProtocolException {

    CloseableHttpClient client = HttpClientBuilder.create().disableAutomaticRetries().build();

    try {
      HttpPost httppost = new HttpPost(localhost(path));

      MultipartEntityBuilder builder = MultipartEntityBuilder.create();

      for (Entry<String, String> entry : files.entrySet()) {
        ContentType contentType = ContentType.create("application/octet-stream");
        String filename = entry.getValue();
        builder =
            builder.addBinaryBody(entry.getKey(), resourceFile(filename), contentType, filename);
      }

      for (Entry<String, String> entry : params.entrySet()) {
        ContentType contentType = ContentType.create("text/plain", "UTF-8");
        builder = builder.addTextBody(entry.getKey(), entry.getValue(), contentType);
      }

      httppost.setEntity(builder.build());

      httppost.addHeader("Cookie", "COOKIE1=a");
      httppost.addHeader("COOKIE", "foo=bar");

      System.out.println("REQUEST " + httppost.getRequestLine());

      UTILS.startMeasure();
      CloseableHttpResponse response = client.execute(httppost);
      UTILS.endMeasure();

      try {
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());

        InputStream resp = response.getEntity().getContent();
        String decoded = IOUtils.toString(resp, "UTF-8");

        return decoded;
      } finally {
        response.close();
      }
    } finally {
      client.close();
    }
  }
Beispiel #17
0
  /*
   * posts an image to the users news feed
   * @param message to show
   * @param image as form data
   * @return the new image id if successful
   */
  public String publishPicture(String msg, Image image, String placeId) throws IOException {
    OAuthRequest request =
        new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node
    request.addHeader("Authorization", "Bearer " + accessTokenString); // authentificate

    // check input to avoid error responses
    if (msg != null && image != null) {
      // facebook requires multipart post structure
      MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.addTextBody("message", msg); // description

      if (placeId != null && !"".equals(placeId)) {
        builder.addTextBody(
            "place", placeId); // add link to FabLab site if property is set in preferences
      }

      // convert image to bytearray and append to multipart
      BufferedImage bimage =
          new BufferedImage(
              image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
      Graphics2D bGr = bimage.createGraphics();
      bGr.drawImage(image, 0, 0, null);
      bGr.dispose();
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ImageIO.write(bimage, "png", baos);
      builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png");

      // generate multipart byte stream and add to payload of post package
      HttpEntity multipart = builder.build();
      ByteArrayOutputStream multipartOutStream =
          new ByteArrayOutputStream((int) multipart.getContentLength());
      multipart.writeTo(multipartOutStream);
      request.addPayload(multipartOutStream.toByteArray());

      // set header of post package
      Header contentType = multipart.getContentType();
      request.addHeader(contentType.getName(), contentType.getValue());

      // send and response answer
      Response response = request.send();
      return response.getBody();
    } else {
      throw new RuntimeException(CONSTANTS.get(FACEBOOK_MESSAGE_IMG_NEEDED));
    }
  }
  private static String uploadToSever(String url, List<NameValuePair> nameValuePairs)
      throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
      MultipartEntityBuilder builder = MultipartEntityBuilder.create();
      builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

      for (int index = 0; index < nameValuePairs.size(); index++) {
        if (nameValuePairs.get(index).getName().equalsIgnoreCase("filename")) {
          builder.addPart(
              nameValuePairs.get(index).getName(),
              new FileBody(new File(nameValuePairs.get(index).getValue())));
        } else {
          builder.addPart(
              nameValuePairs.get(index).getName(),
              new StringBody(nameValuePairs.get(index).getValue()));
        }
      }

      HttpEntity entity = builder.build();
      httpPost.setEntity(entity);

      HttpResponse response = httpClient.execute(httpPost, localContext);

      HttpEntity responseEntity = response.getEntity();

      String strResponse = "";

      if (responseEntity != null) {
        strResponse = EntityUtils.toString(responseEntity);
      }

      return strResponse;

    } catch (IOException e) {
      throw e;
    } finally {
      httpPost = null;
      httpClient = null;
    }
  }
Beispiel #19
0
  public static void main(String[] args) throws UnsupportedEncodingException {

    CloseableHttpClient client = HttpClients.custom().build();
    HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/httpClient");
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    //        multipartEntityBuilder.setCharset(Charset.forName("utf-8"));
    FileBody file = new FileBody(new File("F:\\壁纸\\b.jpg"));
    multipartEntityBuilder.addPart("file", file);
    multipartEntityBuilder.addTextBody("name", "tanghaibin");
    multipartEntityBuilder.addBinaryBody("lick", "骑行".getBytes("utf-8"));
    httpPost.setEntity(multipartEntityBuilder.build());

    try {
      CloseableHttpResponse response = client.execute(httpPost);
      HttpEntity result = response.getEntity();
      System.out.println(result.toString());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  @Override
  public int updateHAProxyConfiguration(List<VirtualMachine> virtualMachines) {
    CloseableHttpResponse response2 = null;
    try {
      CloseableHttpClient httpclient = HttpClients.createDefault();

      HttpPost httpPost = new HttpPost(LOAD_BALANCER_UPDATE_URL);
      String newConfig = HAProxyConfigGenerator.generateConfigFile(virtualMachines);
      LOG.info("New HA Proxy Config:");

      File file = File.createTempFile("new-config", ".cfg");
      FileUtils.writeStringToFile(file, newConfig);
      LOG.info("New HA Proxy File: " + file.getAbsolutePath());
      LOG.info(newConfig);

      HttpEntity httpEntity =
          MultipartEntityBuilder.create()
              .addBinaryBody("file", file, ContentType.create("text/plain"), file.getName())
              .build();

      httpPost.setEntity(httpEntity);

      response2 = httpclient.execute(httpPost);

      LOG.info("HAPRoxy Update: " + response2.getStatusLine().getReasonPhrase());
      HttpEntity entity2 = response2.getEntity();
      EntityUtils.consume(entity2);
      return response2.getStatusLine().getStatusCode();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (response2 != null) {
          response2.close();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return -1;
  }
  public ImageData recognize(byte[] jpeg) {

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addBinaryBody("imgFile", jpeg, ContentType.DEFAULT_BINARY, "cam.jpg");

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost(uri);
    post.addHeader("Authorization", credentials.createAuthorizationHeaderValue());
    post.setEntity(builder.build());

    try {
      HttpResponse response = httpclient.execute(post);
      VisualRecognitionResponse r =
          objectMapper.readValue(
              EntityUtils.toString(response.getEntity()), VisualRecognitionResponse.class);
      return r.getImages().get(0);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
 private void upload(File file) {
   HttpClient client = new DefaultHttpClient();
   HttpPost post = new HttpPost(getUploadUrl());
   MultipartEntityBuilder builder = MultipartEntityBuilder.create();
   builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
   FileBody fb = new FileBody(file);
   builder.addPart("log_file", fb);
   HttpEntity entity = builder.build();
   post.setEntity(entity);
   try {
     HttpResponse response = client.execute(post);
     int statusCode = response.getStatusLine().getStatusCode();
     Log.d(
         ApeicUtil.TAG_HTTP,
         "Status code of uploading " + file.getName() + ": " + String.valueOf(statusCode));
     if (statusCode == 200) {
       file.delete();
     }
   } catch (IOException e) {
     Log.e(ApeicUtil.TAG_HTTP, e.getMessage());
   }
 }
  private HttpEntity buildMultipartEntity() {
    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();

    if (mMap != null && mMap.size() > 0) {
      Iterator<Entry<String, Object>> iterator = mMap.entrySet().iterator();

      while (iterator.hasNext()) {
        Entry<String, Object> entry = iterator.next();
        String key = entry.getKey();
        Object value = entry.getValue();
        if (value instanceof File) {
          multipartEntity.addPart(key, new FileBody((File) value));
        } else {
          // Log.d("key: "+key);
          // Log.d("value: "+value.toString());
          multipartEntity.addTextBody(key, value.toString(), ContentType.APPLICATION_JSON);
        }
      }
    }

    return multipartEntity.build();
  }
  /** 上传文件 */
  public void upload() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
      HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");

      FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
      StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

      HttpEntity reqEntity =
          MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();

      httppost.setEntity(reqEntity);

      System.out.println("executing request " + httppost.getRequestLine());
      CloseableHttpResponse response = httpclient.execute(httppost);
      try {
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
          System.out.println("Response content length: " + resEntity.getContentLength());
        }
        EntityUtils.consume(resEntity);
      } finally {
        response.close();
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        httpclient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Beispiel #25
0
  @Override
  protected Integer doInBackground(Trick... trick) {
    try {
      int level = trick[0].getLevel();
      String videoPath = trick[0].getVideoFilePath();
      String rollPath = trick[0].getDataRollFilePath();
      String pitchPath = trick[0].getDataPitchFilePath();
      String yawPath = trick[0].getDataYawFilePath();
      String altitudePath = trick[0].getDataAltitudeFilePath();
      HttpClient client = new DefaultHttpClient();
      File videoFile = new File(videoPath);
      File rollFile = new File(rollPath);
      File pitchFile = new File(pitchPath);
      File yawFile = new File(yawPath);
      File altitudeFile = new File(altitudePath);
      HttpPost post = new HttpPost("http://skate.3du.es");

      MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
      entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
      entityBuilder.addTextBody("user", "demoUser");
      entityBuilder.addTextBody("level", String.valueOf(level));
      entityBuilder.addBinaryBody("video", videoFile);
      entityBuilder.addBinaryBody("roll", rollFile);
      entityBuilder.addBinaryBody("pitch", pitchFile);
      entityBuilder.addBinaryBody("yaw", yawFile);
      entityBuilder.addBinaryBody("altitude", altitudeFile);
      // add more key/value pairs here as needed

      HttpEntity entity = entityBuilder.build();
      post.setEntity(entity);

      HttpResponse response = client.execute(post);
      HttpEntity httpEntity = response.getEntity();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  public MultipartRequest(
      String url,
      Response.Listener<String> rListener,
      Response.ErrorListener eListener,
      @Nullable HashMap<String, String> head,
      @NonNull String stringPart,
      @NonNull File file,
      @Nullable Map<String, Object> param) {
    super(Method.POST, url, rListener, eListener);

    header = null;
    if (head == null) {
      header = new HashMap<>();
    } else {
      header = (HashMap) head.clone();
    }

    String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
    header.put("Content-Type", "multipart/form-data; boundary=" + boundary);

    // build multi-part
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setBoundary(boundary);
    entityBuilder.addPart(stringPart, new FileBody(file));
    if (param != null) {
      try {
        for (String key : param.keySet()) {
          Object obj = param.get(key);
          String input = obj.toString();
          entityBuilder.addPart(key, new StringBody(input, ContentType.MULTIPART_FORM_DATA));
        }
      } catch (Exception e) {
        VolleyLog.e("Fail to build multipart. " + e.getMessage());
        e.printStackTrace();
      }
    }
    entity = entityBuilder.build();
  }
Beispiel #27
0
  @Test
  public void testPostWithFile() throws Exception {
    HttpPost httpPost = null;
    HttpResponse response = null;

    httpPost = new HttpPost("http://test.cnfol.com:8080/test/index.shtml");

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.addBinaryBody("userName", "吴晓东".getBytes(Consts.UTF_8));
    entityBuilder.addBinaryBody("uploadFileName", "消费明细.xlsx".getBytes(Consts.UTF_8));
    entityBuilder.addTextBody("userPassword", "123456");
    entityBuilder.addTextBody("userId", "10000");
    entityBuilder.addBinaryBody("upload", new File("C:\\Users\\Administrator\\Desktop\\消费明细.xlsx"));
    entityBuilder.setCharset(Consts.UTF_8);

    httpPost.setEntity(entityBuilder.build());
    response = httpClient.execute(httpPost);
    if (response.getStatusLine().getStatusCode() == 200) {
      System.out.println(writeToString(response.getEntity().getContent()));
    } else {
      throw new Exception(response.getStatusLine().toString());
    }
  }
Beispiel #28
0
  /**
   * If Request is MultiPartRequest type, then set MultipartEntity in the httpRequest object.
   *
   * @param httpRequest
   * @param request
   * @throws AuthFailureError
   */
  private static void setMultiPartBody(
      HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError {

    // Return if Request is not MultiPartRequest
    if (!(request instanceof MultiPartRequest)) {
      return;
    }

    // MultipartEntity multipartEntity = new
    // MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    /* example for setting a HttpMultipartMode */
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    // Iterate the fileUploads
    Map<String, File> fileUpload = ((MultiPartRequest) request).getFileUploads();
    for (Map.Entry<String, File> entry : fileUpload.entrySet()) {

      builder.addPart(((String) entry.getKey()), new FileBody((File) entry.getValue()));
    }

    ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
    // Iterate the stringUploads
    Map<String, String> stringUpload = ((MultiPartRequest) request).getStringUploads();
    for (Map.Entry<String, String> entry : stringUpload.entrySet()) {
      try {
        builder.addPart(
            ((String) entry.getKey()), new StringBody((String) entry.getValue(), contentType));
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    httpRequest.setEntity(builder.build());
  }
  /*.................................................................................................................*/
  public Object getProgramArguments(String dataFileName, boolean isPreflight) {
    MultipartEntityBuilder arguments = MultipartEntityBuilder.create();
    StringBuffer sb = new StringBuffer();

    if (!isPreflight) {
      getArguments(
          arguments,
          sb,
          dataFileName,
          proteinModel,
          dnaModel,
          otherOptions,
          bootstrapreps,
          bootstrapSeed,
          numRuns,
          outgroupTaxSetString,
          multipleModelFileName,
          false);
      logln("RAxML arguments: \n" + sb.toString() + "\n");
    } else {
      getArguments(
          arguments,
          sb,
          dataFileName,
          proteinModel,
          dnaModel,
          otherOptions,
          bootstrapreps,
          bootstrapSeed,
          numRuns,
          outgroupTaxSetString,
          multipleModelFileName,
          true);
    }
    return arguments;
  }
Beispiel #30
0
 public static String upload(String url, File file, Map<String, String> params, boolean isHttps) {
   HttpClient client = isHttps ? createSSLClientDefault() : HttpClients.createDefault();
   HttpPost post = new HttpPost(url);
   FileBody bin = new FileBody(file);
   MultipartEntityBuilder builder = MultipartEntityBuilder.create();
   Set<String> keySet = params.keySet();
   for (String key : keySet) {
     builder.addTextBody(key, params.get(key));
   }
   builder.addPart("media", bin);
   HttpEntity entity = builder.build();
   post.setEntity(entity);
   try {
     HttpResponse response = client.execute(post);
     return httpClientResponse(response);
   } catch (ClientProtocolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return null;
 }