@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());
 }
Beispiel #2
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;
  }
Beispiel #3
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;
    }
Beispiel #4
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());
    }
  }
  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();
    }
  }
  /*
   * 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));
    }
  }
Beispiel #7
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();
    }
  }
  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);
    }
  }
Beispiel #9
0
  public HttpEntity buildBody(Email email) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    // We are using an API key
    if (this.username != null) {
      builder.addTextBody("api_user", this.username);
      builder.addTextBody("api_key", this.password);
    }

    String[] tos = email.getTos();
    String[] tonames = email.getToNames();
    String[] ccs = email.getCcs();
    String[] bccs = email.getBccs();

    // If SMTPAPI Header is used, To is still required. #workaround.
    if (tos.length == 0) {
      builder.addTextBody(
          String.format(PARAM_TO, 0), email.getFrom(), ContentType.create(TEXT_PLAIN, UTF_8));
    }
    for (int i = 0, len = tos.length; i < len; i++)
      builder.addTextBody(PARAM_TO, tos[i], ContentType.create("text/plain", "UTF-8"));
    for (int i = 0, len = tonames.length; i < len; i++)
      builder.addTextBody(PARAM_TONAME, tonames[i], ContentType.create("text/plain", "UTF-8"));
    for (int i = 0, len = ccs.length; i < len; i++)
      builder.addTextBody(PARAM_CC, ccs[i], ContentType.create("text/plain", "UTF-8"));
    for (int i = 0, len = bccs.length; i < len; i++)
      builder.addTextBody(PARAM_BCC, bccs[i], ContentType.create(TEXT_PLAIN, UTF_8));
    // Files
    if (email.getAttachments().size() > 0) {
      Iterator it = email.getAttachments().entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        builder.addBinaryBody(
            String.format(PARAM_FILES, entry.getKey()), (InputStream) entry.getValue());
      }
    }

    if (email.getContentIds().size() > 0) {
      Iterator it = email.getContentIds().entrySet().iterator();
      while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        builder.addTextBody(
            String.format(PARAM_CONTENTS, entry.getKey()), (String) entry.getValue());
      }
    }

    if (email.getHeaders().size() > 0)
      builder.addTextBody(
          PARAM_HEADERS,
          new JSONObject(email.getHeaders()).toString(),
          ContentType.create(TEXT_PLAIN, UTF_8));

    if (email.getFrom() != null && !email.getFrom().isEmpty())
      builder.addTextBody(PARAM_FROM, email.getFrom(), ContentType.create(TEXT_PLAIN, UTF_8));

    if (email.getFromName() != null && !email.getFromName().isEmpty())
      builder.addTextBody(
          PARAM_FROMNAME, email.getFromName(), ContentType.create(TEXT_PLAIN, UTF_8));

    if (email.getReplyTo() != null && !email.getReplyTo().isEmpty())
      builder.addTextBody(PARAM_REPLYTO, email.getReplyTo(), ContentType.create(TEXT_PLAIN, UTF_8));

    if (email.getSubject() != null && !email.getSubject().isEmpty())
      builder.addTextBody(PARAM_SUBJECT, email.getSubject(), ContentType.create(TEXT_PLAIN, UTF_8));

    if (email.getHtml() != null && !email.getHtml().isEmpty())
      builder.addTextBody(PARAM_HTML, email.getHtml(), ContentType.create(TEXT_PLAIN, UTF_8));

    if (email.getText() != null && !email.getText().isEmpty())
      builder.addTextBody(PARAM_TEXT, email.getText(), ContentType.create(TEXT_PLAIN, UTF_8));

    String tmpString = email.smtpapi.jsonString();
    if (!tmpString.equals("{}"))
      builder.addTextBody(PARAM_XSMTPAPI, tmpString, ContentType.create(TEXT_PLAIN, UTF_8));

    return builder.build();
  }