@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());
 }
예제 #2
0
  private String getContentCharset(byte[] content, Metadata metadata) {
    String charset = null;

    // check if the server specified a charset
    String specifiedContentType = metadata.getFirstValue(HttpHeaders.CONTENT_TYPE);
    try {
      if (specifiedContentType != null) {
        ContentType parsedContentType = ContentType.parse(specifiedContentType);
        charset = parsedContentType.getCharset().name();
      }
    } catch (Exception e) {
      charset = null;
    }

    // filter HTML tags
    CharsetDetector detector = new CharsetDetector();
    detector.enableInputFilter(true);
    // give it a hint
    detector.setDeclaredEncoding(charset);
    detector.setText(content);
    try {
      CharsetMatch charsetMatch = detector.detect();
      if (charsetMatch != null) {
        charset = charsetMatch.getName();
      }
    } catch (Exception e) {
      // ignore and leave the charset as-is
    }
    return charset;
  }
예제 #3
0
  @Test
  public void testUpdateWithTagWithSchemeAndLabel() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.addCodedDiagnosis().addCoding().setCode("AAA");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\"");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    CloseableHttpResponse status = ourClient.execute(httpPost);
    assertEquals(1, ourReportProvider.getLastTags().size());
    assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0));
    IOUtils.closeQuietly(status.getEntity().getContent());

    httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\";   ");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));
    status = ourClient.execute(httpPost);
    IOUtils.closeQuietly(status.getEntity().getContent());

    assertEquals(1, ourReportProvider.getLastTags().size());
    assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0));
  }
예제 #4
0
  // Try to add twice
  @Test
  public void add_delete_dataset_2() {
    checkNotThere(dsTest);

    File f = new File("testing/config-ds-1.ttl");
    {
      org.apache.http.entity.ContentType ct =
          org.apache.http.entity.ContentType.parse(
              WebContent.contentTypeTurtle + "; charset=" + WebContent.charsetUTF8);
      HttpEntity e = new FileEntity(f, ct);
      execHttpPost(ServerTest.urlRoot + "$/" + opDatasets, e);
    }
    // Check exists.
    checkExists(dsTest);
    try {
      org.apache.http.entity.ContentType ct =
          org.apache.http.entity.ContentType.parse(
              WebContent.contentTypeTurtle + "; charset=" + WebContent.charsetUTF8);
      HttpEntity e = new FileEntity(f, ct);
      execHttpPost(ServerTest.urlRoot + "$/" + opDatasets, e);
    } catch (HttpException ex) {
      assertEquals(HttpSC.CONFLICT_409, ex.getResponseCode());
    }
    // Check exists.
    checkExists(dsTest);
    deleteDataset(dsTest);
  }
예제 #5
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;
  }
예제 #6
0
 private ContentType receiveWithCharsetParameter(ContentType contentType, Charset charset) {
   if (contentType.getCharset() != null) {
     return contentType;
   }
   final String mimeType = contentType.getMimeType();
   if (mimeType.equals(ContentType.TEXT_PLAIN.getMimeType())
       || AbstractFutureCallback.ODATA_MIME_TYPE.matcher(mimeType).matches()) {
     return contentType.withCharset(charset);
   }
   return contentType;
 }
  @Test
  public void testUpdateWithoutConditionalUrl() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());

    assertEquals("Patient/2", new IdType(ourLastId).toUnqualified().getValue());
    assertEquals("Patient/2", ourLastIdParam.toUnqualified().getValue());
    assertNull(ourLastConditionalUrl);
  }
예제 #8
0
  @Override
  public boolean sendMessageToEndPoint(final HttpMessage message) {
    Assert.notNull(this.httpClient);

    try {
      final HttpPost request = new HttpPost(message.getUrl().toURI());
      request.addHeader("Content-Type", message.getContentType());

      final StringEntity entity =
          new StringEntity(message.getMessage(), ContentType.create(message.getContentType()));
      request.setEntity(entity);

      final ResponseHandler<Boolean> handler =
          response -> response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
      final HttpRequestFutureTask<Boolean> task =
          this.requestExecutorService.execute(request, HttpClientContext.create(), handler);
      if (message.isAsynchronous()) {
        return true;
      }
      return task.get();
    } catch (final RejectedExecutionException e) {
      LOGGER.warn(e.getMessage(), e);
      return false;
    } catch (final Exception e) {
      LOGGER.debug(e.getMessage(), e);
      return false;
    }
  }
예제 #9
0
 @Override
 protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
   Integer streamId =
       msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
   if (streamId == null) {
     logger.error("HttpResponseHandler unexpected message received: " + msg);
     return;
   }
   onResponseReceived(ctx, streamIdUrlMap.get(streamId));
   Map.Entry<ChannelFuture, ChannelPromise> entry = streamIdPromiseMap.get(streamId);
   if (entry == null) {
     logger.error("Message received for unknown stream id " + streamId);
   } else {
     // Do stuff with the message (for now just print it)
     ByteBuf content = msg.content();
     ContentType contentType = ContentType.parse(msg.headers().get(HttpHeaderNames.CONTENT_TYPE));
     if (content.isReadable()) {
       int contentLength = content.readableBytes();
       byte[] arr = new byte[contentLength];
       content.readBytes(arr);
       handleContent(arr, ctx, contentType);
     }
     entry.getValue().setSuccess();
   }
 }
예제 #10
0
  @Test
  public void testUpdateNoResponse() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.addCodedDiagnosis().addCoding().setCode("AAA");

    String encoded = ourCtx.newXmlParser().encodeResourceToString(dr);
    ourLog.info("OUT: {}", encoded);

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPost.setEntity(
        new StringEntity(encoded, ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);
    try {
      ourLog.info(IOUtils.toString(status.getEntity().getContent()));
      assertEquals(200, status.getStatusLine().getStatusCode());
      assertEquals(
          "http://localhost:" + ourPort + "/DiagnosticReport/001/_history/002",
          status.getFirstHeader("location").getValue());
    } finally {
      IOUtils.closeQuietly(status.getEntity().getContent());
    }
  }
예제 #11
0
  @Test
  public void testUpdateWithWrongResourceType() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/AAAAAA");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    assertEquals(400, status.getStatusLine().getStatusCode());

    String expected =
        "<OperationOutcome xmlns=\"http://hl7.org/fhir\"><issue><severity value=\"error\"/><details value=\"Failed to parse request body as XML resource. Error was: DataFormatException at [[row,col {unknown-source}]: [1,1]]: Incorrect resource type found, expected &quot;DiagnosticReport&quot; but found &quot;Patient&quot;\"/></issue></OperationOutcome>";
    assertEquals(expected, responseContent);
  }
예제 #12
0
  /**
   * Uploads a {@code File} with PRIVATE read access.
   *
   * @param uri upload {@link URI}
   * @param contentTypeString content type
   * @param contentFile the file to upload
   * @throws IOException
   */
  public static void uploadPrivateContent(
      final URI uri, final String contentTypeString, final File contentFile) throws IOException {

    LOGGER.info(
        "uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    FileEntity fileEntity = new FileEntity(contentFile, contentType);
    httpPut.setEntity(fileEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
      throw new IOException(
          String.format(
              "An error occurred while trying to upload private file - %d: %s",
              statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info(
        "uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]",
        new Object[] {uri, contentTypeString, contentFile});
  }
예제 #13
0
  public void run() {
    for (Object MSISDN : mListMSISDN) {
      String TextResponse = "";

      String XMLReqeust = String.format(Template, MSISDN);

      HttpPost mPost = new HttpPost(URL);

      StringEntity mEntity = new StringEntity(XMLReqeust, ContentType.create("text/xml", "UTF-8"));

      mPost.setEntity(mEntity);
      HttpClient mClient = new DefaultHttpClient();
      try {
        HttpResponse response = mClient.execute(mPost);

        HttpEntity entity = response.getEntity();
        TextResponse = EntityUtils.toString(entity);

        System.out.println(TextResponse);

        EntityUtils.consume(entity);
      } catch (Exception ex) {
        mLog.log.error(ex);
      } finally {
        mLog.log.debug("REQUEST --> " + XMLReqeust);
        mLog.log.debug("RESPONSE --> " + TextResponse);
      }
    }
    mLog.log.debug("KET THUC THEAD " + ThreadIndex);
  }
예제 #14
0
  @Test
  public void testUpdate() throws Exception {

    Patient patient = new Patient();
    patient.addIdentifier().setValue("002");

    HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/001");
    httpPost.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(patient),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPost);

    String responseContent = IOUtils.toString(status.getEntity().getContent());
    IOUtils.closeQuietly(status.getEntity().getContent());

    ourLog.info("Response was:\n{}", responseContent);

    OperationOutcome oo =
        ourCtx.newXmlParser().parseResource(OperationOutcome.class, responseContent);
    assertEquals("OODETAILS", oo.getIssueFirstRep().getDetails().getValue());

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("location").getValue());
    assertEquals(
        "http://localhost:" + ourPort + "/Patient/001/_history/002",
        status.getFirstHeader("content-location").getValue());
  }
예제 #15
0
  @Test
  public void testUpdateWithVersion() throws Exception {

    DiagnosticReport dr = new DiagnosticReport();
    dr.setId("001");
    dr.getIdentifier().setValue("001");

    HttpPut httpPut = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001");
    httpPut.addHeader("Content-Location", "/DiagnosticReport/001/_history/004");
    httpPut.setEntity(
        new StringEntity(
            ourCtx.newXmlParser().encodeResourceToString(dr),
            ContentType.create(Constants.CT_FHIR_XML, "UTF-8")));

    HttpResponse status = ourClient.execute(httpPut);
    IOUtils.closeQuietly(status.getEntity().getContent());

    // String responseContent =
    // IOUtils.toString(status.getEntity().getContent());
    // ourLog.info("Response was:\n{}", responseContent);

    assertEquals(200, status.getStatusLine().getStatusCode());
    assertEquals(
        "http://localhost:" + ourPort + "/DiagnosticReport/001/_history/002",
        status.getFirstHeader("Location").getValue());
  }
예제 #16
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();
    }
  }
예제 #17
0
 private static void addTestDataset() {
   File f = new File("testing/config-ds-1.ttl");
   org.apache.http.entity.ContentType ct =
       org.apache.http.entity.ContentType.parse(
           WebContent.contentTypeTurtle + "; charset=" + WebContent.charsetUTF8);
   HttpEntity e = new FileEntity(f, ct);
   execHttpPost(ServerTest.urlRoot + "$/" + opDatasets, e);
 }
예제 #18
0
 @SuppressWarnings("unused")
 public HttpCommandResponse execute(String url, String body, String mimeType, String charsetName)
     throws IOException {
   HttpPost httpPut = new HttpPost(url);
   httpPut.setEntity(
       new StringEntity(body, ContentType.create(mimeType, Charset.forName(charsetName))));
   return new HttpCommandResponse(shellHttpClient.getHttpClient().execute(httpPut));
 }
 private Content handleEntity(final HttpEntity entity) throws IOException {
   Content content = null;
   if (entity != null) {
     content = new Content(EntityUtils.toByteArray(entity), ContentType.getOrDefault(entity));
   } else {
     content = Content.NO_CONTENT;
   }
   return content;
 }
예제 #20
0
  /* POST /oozie/v1/jobs (request XML; contains URL, response JSON)
  Content-Type: application/json;charset=UTF-8
  Content-Length: 45
  Server: Apache-Coyote/1.1
  Date: Thu, 14 Feb 2013 18:10:52 GMT
  */
  public String oozieSubmitJob(String user, String password, String request, int status)
      throws IOException, URISyntaxException {
    getMock("OOZIE")
        .expect()
        .method("POST")
        .pathInfo("/v1/jobs")
        .respond()
        .status(HttpStatus.SC_CREATED)
        .content(getResourceBytes("oozie-jobs-submit-response.json"))
        .contentType("application/json");
    // System.out.println( "REQUEST LENGTH = " + request.length() );

    URL url =
        new URL(
            getUrl("OOZIE")
                + "/v1/jobs?action=start"
                + (isUseGateway() ? "" : "&user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    DefaultHttpClient client = new DefaultHttpClient();
    client
        .getCredentialsProvider()
        .setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(user, password));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost(url.toURI());
    //    post.getParams().setParameter( "action", "start" );
    StringEntity entity = new StringEntity(request, ContentType.create("application/xml", "UTF-8"));
    post.setEntity(entity);
    post.setHeader("X-XSRF-Header", "ksdjfhdsjkfhds");
    HttpResponse response = client.execute(targetHost, post, localContext);
    assertThat(response.getStatusLine().getStatusCode(), is(status));
    String json = EntityUtils.toString(response.getEntity());

    //    String json = given()
    //        .log().all()
    //        .auth().preemptive().basic( user, password )
    //        .queryParam( "action", "start" )
    //        .contentType( "application/xml;charset=UTF-8" )
    //        .content( request )
    //        .expect()
    //        .log().all()
    //        .statusCode( status )
    //        .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" +
    // user ) ).asString();
    // System.out.println( "JSON=" + json );
    String id = from(json).getString("id");
    return id;
  }
예제 #21
0
  /**
   * Create Olingo2 Application with custom HTTP client builder.
   *
   * @param serviceUri Service Application base URI.
   * @param builder custom HTTP client builder.
   */
  public Olingo2AppImpl(String serviceUri, HttpAsyncClientBuilder builder) {
    setServiceUri(serviceUri);

    if (builder == null) {
      this.client = HttpAsyncClients.createDefault();
    } else {
      this.client = builder.build();
    }
    this.client.start();
    this.contentType = ContentType.create("application/json", Consts.UTF_8);
  }
예제 #22
0
  @Test
  @Ignore("Works in isolation but fails when executed as part of test suite")
  public void testUpload() throws Exception {
    stubFor(
        put(urlEqualTo("/endpoint"))
            .withHeader(CONTENT_TYPE, matching("mock/type"))
            .willReturn(aResponse().withStatus(SC_NO_CONTENT)));

    File file = File.createTempFile("unit-test", ".tmp");
    endpoint.upload(file, ContentType.create("mock/type"));
  }
 private CoverallsResponse parseResponse(final HttpResponse response)
     throws ProcessingException, IOException {
   HttpEntity entity = response.getEntity();
   ContentType contentType = ContentType.getOrDefault(entity);
   InputStreamReader reader = null;
   try {
     reader = new InputStreamReader(entity.getContent(), contentType.getCharset());
     CoverallsResponse cr = objectMapper.readValue(reader, CoverallsResponse.class);
     if (cr.isError()) {
       throw new ProcessingException(getResponseErrorMessage(response, cr.getMessage()));
     }
     return cr;
   } catch (JsonProcessingException ex) {
     throw new ProcessingException(getResponseErrorMessage(response, ex.getMessage()), ex);
   } catch (IOException ex) {
     throw new IOException(getResponseErrorMessage(response, ex.getMessage()), ex);
   } finally {
     IOUtil.close(reader);
   }
 }
 @Override
 public CloseableHttpResponse sendRequestPOST(Server server, Map<String, String> data)
     throws ClientProtocolException, IOException {
   CloseableHttpClient client = HttpClients.createDefault();
   HttpPost post = new HttpPost(getRequestUri(server, data));
   HttpEntity entity =
       new StringEntity(
           getRequestEncodedUrl(server, data),
           ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
   post.setEntity(entity);
   return client.execute(post);
 }
예제 #25
0
 public HttpResponse returnResponse() throws IOException {
   assertNotConsumed();
   try {
     HttpEntity entity = this.response.getEntity();
     if (entity != null) {
       this.response.setEntity(
           new ByteArrayEntity(EntityUtils.toByteArray(entity), ContentType.getOrDefault(entity)));
     }
     return this.response;
   } finally {
     this.consumed = true;
   }
 }
예제 #26
0
 public static synchronized void post(String url, Object object) {
   try {
     String jsonString = jacksonObjectMapper.writeValueAsString(object);
     HttpPost request = new HttpPost(url);
     StringEntity params = new StringEntity(jsonString, ContentType.create("application/json"));
     request.addHeader("Content-Type", "application/json");
     request.setEntity(params);
     HttpResponse httpResponse = httpClient.execute(request);
     httpResponse.getStatusLine();
   } catch (Exception e) {
     System.out.println(e.getMessage());
   }
 }
예제 #27
0
 static int putUrlAsString(String content, String url) throws HTTPException {
   int status = 0;
   try {
     try (HTTPMethod m = HTTPFactory.Put(url)) {
       m.setRequestContent(
           new StringEntity(content, ContentType.create("application/text", "UTF-8")));
       status = m.execute();
     }
   } catch (UnsupportedCharsetException uce) {
     throw new HTTPException(uce);
   }
   return status;
 }
예제 #28
0
 /** @since 4.2 */
 public NByteArrayEntity(final byte[] b, final ContentType contentType) {
   super();
   Args.notNull(b, "Source byte array");
   this.b = b;
   this.off = 0;
   this.len = b.length;
   this.buf = ByteBuffer.wrap(b);
   this.content = b;
   this.buffer = this.buf;
   if (contentType != null) {
     setContentType(contentType.toString());
   }
 }
  @Test
  public void testGetLocation() throws Exception {
    LocationRepository repository = container.getInjector().getInstance(LocationRepository.class);

    String id = repository.create(new Location("foo", 0, 0)).getId();
    HttpResponse httpResponse = container.execute(new HttpGet("/location/" + id));
    assertEquals(HttpURLConnection.HTTP_OK, httpResponse.getStatusLine().getStatusCode());
    HttpEntity entity = httpResponse.getEntity();
    assertEquals(ContentType.APPLICATION_JSON.getMimeType(), ContentType.get(entity).getMimeType());
    String content = EntityUtils.toString(entity);
    ObjectMapper om = new ObjectMapper();
    Map<String, ?> response = om.readValue(content, new TypeReference<Map<String, ?>>() {});
    assertEquals(id, response.get("id"));
  }
예제 #30
0
  public static Reader createReaderFromResponse(HttpResponse theResponse)
      throws IllegalStateException, IOException {
    HttpEntity entity = theResponse.getEntity();
    if (entity == null) {
      return new StringReader("");
    }
    Charset charset = null;
    if (entity.getContentType() != null
        && entity.getContentType().getElements() != null
        && entity.getContentType().getElements().length > 0) {
      ContentType ct = ContentType.get(entity);
      charset = ct.getCharset();
    }
    if (charset == null) {
      if (Constants.STATUS_HTTP_204_NO_CONTENT != theResponse.getStatusLine().getStatusCode()) {
        ourLog.warn("Response did not specify a charset.");
      }
      charset = Charset.forName("UTF-8");
    }

    Reader reader = new InputStreamReader(theResponse.getEntity().getContent(), charset);
    return reader;
  }