コード例 #1
0
  /**
   * 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;
    }
  }
コード例 #2
0
 /*.................................................................................................................*/
 public void prepareBuilder(MultipartEntityBuilder builder, String cipresTool, String jobID) {
   if (builder != null) {
     builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
     builder.addTextBody("tool", cipresTool);
     if (StringUtil.notEmpty(jobID)) builder.addTextBody("metadata.clientJobId", jobID);
     builder.addTextBody("metadata.statusEmail", "true");
     builder.addTextBody("vparam.runtime_", "0.50", ContentType.TEXT_PLAIN);
   }
 }
コード例 #3
0
  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());
    }
  }
コード例 #4
0
ファイル: Http.java プロジェクト: Carboni/jenkins-jobs
  /**
   * 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);
    }
  }
コード例 #5
0
 @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());
 }
コード例 #6
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));
    }
  }
コード例 #7
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;
 }
コード例 #8
0
ファイル: UpLoader.java プロジェクト: ABarredo/TheSkateApp
  @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;
  }
コード例 #9
0
ファイル: Http.java プロジェクト: yang-yy/ssh-base
  @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());
    }
  }
コード例 #10
0
  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();
    }
  }
コード例 #11
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();
    }
  }
コード例 #12
0
  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();
  }
コード例 #13
0
ファイル: HttpClientUtils.java プロジェクト: angelwsin/weixin
 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;
 }
コード例 #14
0
  static void getTokensFromCode() {
    access_token = null;
    expires_in = -1;
    token_start_time = -1;
    refresh_token = null;
    new File("/home/sead/refresh.txt").delete();

    if (gProps == null) {
      initGProps();
    }
    // Query for token now that user has gone through browser part
    // of
    // flow
    HttpPost tokenRequest = new HttpPost(gProps.token_uri);

    MultipartEntityBuilder tokenRequestParams = MultipartEntityBuilder.create();
    tokenRequestParams.addTextBody("client_id", gProps.client_id);
    tokenRequestParams.addTextBody("client_secret", gProps.client_secret);
    tokenRequestParams.addTextBody("code", device_code);
    tokenRequestParams.addTextBody("grant_type", "http://oauth.net/grant_type/device/1.0");

    HttpEntity reqEntity = tokenRequestParams.build();

    tokenRequest.setEntity(reqEntity);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    try {
      response = httpclient.execute(tokenRequest);

      if (response.getStatusLine().getStatusCode() == 200) {
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
          String responseJSON = EntityUtils.toString(resEntity);
          ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON);
          access_token = root.get("access_token").asText();
          refresh_token = root.get("refresh_token").asText();
          token_start_time = System.currentTimeMillis() / 1000;
          expires_in = root.get("expires_in").asInt();
        }
      } else {
        log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase());
      }
    } catch (ParseException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      if (response != null) {
        try {
          response.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      try {
        httpclient.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
コード例 #15
0
ファイル: SendGrid.java プロジェクト: amitquill/GNPNew
  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();
  }
コード例 #16
0
 /*.................................................................................................................*/
 void addArgument(MultipartEntityBuilder builder, StringBuffer sb, String param, String value) {
   if (builder != null) builder.addTextBody(param, value);
   if (sb != null) sb.append("\n  " + param + " = " + value);
 }