public HttpPost createPostMethod(String url, Object postData) {
    try {
      byte[] rawData;

      if (postData instanceof byte[]) {
        rawData = (byte[]) postData;
      } else {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(postData);
        oos.close();
        rawData = baos.toByteArray();
      }

      InputStream is = new ByteArrayInputStream(rawData);

      HttpPost httpPost = new HttpPost(url);
      BasicHttpEntity entity = new BasicHttpEntity();
      entity.setContentType("application/octet-stream");
      entity.setContentLength(rawData.length);
      entity.setContent(is);
      httpPost.setEntity(entity);

      RequestConfig requestConfig =
          RequestConfig.copy(HAZELCAST_REQUEST_CONFIG)
              .setSocketTimeout(TIMEOUT)
              .setConnectTimeout(TIMEOUT)
              .setConnectionRequestTimeout(TIMEOUT)
              .build();
      httpPost.setConfig(requestConfig);
      return httpPost;
    } catch (IOException e) {
      throw new RuntimeException("Error POST-ing data", e);
    }
  }
コード例 #2
0
  private static HttpEntity entityFromOkHttpResponse(Response response) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();
    ResponseBody body = response.body();

    entity.setContent(body.byteStream());
    entity.setContentLength(body.contentLength());
    entity.setContentEncoding(response.header("Content-Encoding"));

    if (body.contentType() != null) {
      entity.setContentType(body.contentType().type());
    }
    return entity;
  }
コード例 #3
0
 /**
  * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}.
  *
  * @param connection
  * @return an HttpEntity populated with data from <code>connection</code>.
  */
 private static HttpEntity entityFromConnection(HttpURLConnection connection) {
   BasicHttpEntity entity = new BasicHttpEntity();
   InputStream inputStream;
   try {
     inputStream = connection.getInputStream();
   } catch (IOException ioe) {
     inputStream = connection.getErrorStream();
   }
   entity.setContent(inputStream);
   entity.setContentLength(connection.getContentLength());
   entity.setContentEncoding(connection.getContentEncoding());
   entity.setContentType(connection.getContentType());
   return entity;
 }
コード例 #4
0
ファイル: l.java プロジェクト: gdkjrygh/CompSecurity
 private static HttpEntity a(HttpURLConnection httpurlconnection) {
   BasicHttpEntity basichttpentity = new BasicHttpEntity();
   java.io.InputStream inputstream;
   try {
     inputstream = httpurlconnection.getInputStream();
   } catch (IOException ioexception) {
     ioexception = httpurlconnection.getErrorStream();
   }
   basichttpentity.setContent(inputstream);
   basichttpentity.setContentLength(httpurlconnection.getContentLength());
   basichttpentity.setContentEncoding(httpurlconnection.getContentEncoding());
   basichttpentity.setContentType(httpurlconnection.getContentType());
   return basichttpentity;
 }
コード例 #5
0
ファイル: MainActivity.java プロジェクト: jreznot/diy-remote
    @Override
    protected String doInBackground(String... params) {
      Context context = getApplicationContext();
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

      String serviceUrlString = prefs.getString("connection.url", null);
      if (serviceUrlString != null) {
        if (!serviceUrlString.endsWith("/")) serviceUrlString += "/";

        Command command = new Command();
        command.actionName = params[0];

        Gson gson = new Gson();
        String commandContent = gson.toJson(command);

        HttpPost executePost = new HttpPost(serviceUrlString + "action/execute");
        BasicHttpEntity httpEntity = new BasicHttpEntity();
        httpEntity.setContentType("application/json");
        try {
          httpEntity.setContent(new ByteArrayInputStream(commandContent.getBytes("UTF-8")));
        } catch (UnsupportedEncodingException e) {
          throw new RuntimeException(e);
        }

        executePost.setEntity(httpEntity);
        HttpClient client = new DefaultHttpClient();

        try {
          HttpResponse executeResult = client.execute(executePost);
          if (executeResult.getStatusLine().getStatusCode() == HTTP_STATUS_OK) {
            InputStream content = executeResult.getEntity().getContent();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(content));
            StringBuilder contentBuilder = new StringBuilder();

            String line;
            while ((line = rd.readLine()) != null) {
              contentBuilder.append(line).append("\n");
            }

            Result result = gson.fromJson(contentBuilder.toString(), Result.class);
            return result.message;
          }
        } catch (IOException e) {
          return null;
        }
      }
      return null;
    }
コード例 #6
0
ファイル: ApiServer.java プロジェクト: ngtuna/cloudstack-gre
  // FIXME: rather than isError, we might was to pass in the status code to give more flexibility
  private void writeResponse(
      HttpResponse resp,
      final String responseText,
      final int statusCode,
      String responseType,
      String reasonPhrase) {
    try {
      resp.setStatusCode(statusCode);
      resp.setReasonPhrase(reasonPhrase);

      BasicHttpEntity body = new BasicHttpEntity();
      if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
        // JSON response
        body.setContentType(jsonContentType);
        if (responseText == null) {
          body.setContent(
              new ByteArrayInputStream(
                  "{ \"error\" : { \"description\" : \"Internal Server Error\" } }"
                      .getBytes("UTF-8")));
        }
      } else {
        body.setContentType("text/xml");
        if (responseText == null) {
          body.setContent(
              new ByteArrayInputStream("<error>Internal Server Error</error>".getBytes("UTF-8")));
        }
      }

      if (responseText != null) {
        body.setContent(new ByteArrayInputStream(responseText.getBytes("UTF-8")));
      }
      resp.setEntity(body);
    } catch (Exception ex) {
      s_logger.error("error!", ex);
    }
  }
コード例 #7
0
  @Test
  public void testGetContentType() throws Exception {
    String input = "0123456789";
    BasicHttpEntity basic;
    PartiallyRepeatableHttpEntity replay;

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentType(), nullValue());

    basic = new BasicHttpEntity();
    basic.setContent(new ByteArrayInputStream(input.getBytes(UTF8)));
    basic.setContentType(ContentType.APPLICATION_JSON.getMimeType());
    replay = new PartiallyRepeatableHttpEntity(basic, 5);
    assertThat(replay.getContentType().getValue(), is("application/json"));
  }
コード例 #8
0
  /**
   * 执行HTTP请求之后获取到的数据流.
   *
   * @param connection
   * @return
   */
  private HttpEntity entityFromURLConnwction(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
      inputStream = connection.getInputStream();
    } catch (IOException e) {
      e.printStackTrace();
      inputStream = connection.getErrorStream();
    }

    // TODO : GZIP
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());

    return entity;
  }