org.apache.http.entity.ByteArrayEntity Java Examples

The following examples show how to use org.apache.http.entity.ByteArrayEntity. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ODataTestUtils.java    From product-ei with Apache License 2.0 7 votes vote down vote up
public static int sendPUT(String endpoint, String content, Map<String, String> headers) throws IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpPut httpPut = new HttpPut(endpoint);
	for (String headerType : headers.keySet()) {
		httpPut.setHeader(headerType, headers.get(headerType));
	}
	if (null != content) {
		HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
		if (headers.get("Content-Type") == null) {
			httpPut.setHeader("Content-Type", "application/json");
		}
		httpPut.setEntity(httpEntity);
	}
	HttpResponse httpResponse = httpClient.execute(httpPut);
	return httpResponse.getStatusLine().getStatusCode();
}
 
Example #2
Source File: ClientInvoker.java    From dubbo-plus with Apache License 2.0 6 votes vote down vote up
@Test
public void invokeSayHello(){
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://localhost:8080/net.dubboclub.restful.api.FirstRestfulService1/sayHello/1.0.1/all");
    Map<String,String> requestEntity = new HashMap<String,String>();
    requestEntity.put("arg1","Bieber");
    HttpEntity httpEntity = new ByteArrayEntity(JSON.toJSONBytes(requestEntity));
    httpPost.setEntity(httpEntity);
    try {
        CloseableHttpResponse response =  httpclient.execute(httpPost);
        System.out.println(response.getStatusLine());
        HttpEntity entity2 = response.getEntity();
        // do something useful with the response body
        // and ensure it is fully consumed
        System.out.println(EntityUtils.toString(entity2));
        response.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #3
Source File: InfluxDBPublisher.java    From beam with Apache License 2.0 6 votes vote down vote up
private static void publishNexmark(
    final Collection<Map<String, Object>> results, final InfluxDBSettings settings)
    throws Exception {

  final HttpClientBuilder builder = provideHttpBuilder(settings);
  final HttpPost postRequest = providePOSTRequest(settings);
  final StringBuilder metricBuilder = new StringBuilder();
  results.forEach(
      map ->
          metricBuilder
              .append(map.get("measurement"))
              .append(",")
              .append(getKV(map, "runner"))
              .append(" ")
              .append(getKV(map, "runtimeMs"))
              .append(",")
              .append(getKV(map, "numResults"))
              .append(" ")
              .append(map.get("timestamp"))
              .append('\n'));

  postRequest.setEntity(
      new GzipCompressingEntity(new ByteArrayEntity(metricBuilder.toString().getBytes(UTF_8))));

  executeWithVerification(postRequest, builder);
}
 
Example #4
Source File: HttpHandlerIntegrationTest.java    From blueflood with Apache License 2.0 6 votes vote down vote up
@Test
public void testCompressedRequests() throws Exception{

    URIBuilder builder = getMetricsURIBuilder()
            .setPath("/v2.0/acTEST/ingest");

    HttpPost post = new HttpPost( builder.build() );
    String content = generateJSONMetricsData();
    ByteArrayOutputStream baos = new ByteArrayOutputStream(content.length());
    GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
    gzipOut.write(content.getBytes());
    gzipOut.close();
    ByteArrayEntity entity = new ByteArrayEntity(baos.toByteArray());
    //Setting the content encoding to gzip
    entity.setContentEncoding("gzip");
    baos.close();
    post.setEntity(entity);
    HttpResponse response = client.execute(post);

    try {
        assertEquals( 200, response.getStatusLine().getStatusCode() );
    }
    finally {
        EntityUtils.consume( response.getEntity() ); // Releases connection apparently
    }
}
 
Example #5
Source File: HttpRpcClient.java    From tangyuan2 with GNU General Public License v3.0 6 votes vote down vote up
private String sendPostRequest(String url, byte[] buffer, String header) throws Throwable {
	// TODO: 默认值设置
	CloseableHttpClient httpclient = HttpClients.createDefault();
	try {
		URI uri = new URI(url);
		HttpPost httpost = new HttpPost(uri);
		ByteArrayEntity byteArrayEntity = new ByteArrayEntity(buffer, ContentType.create(header, "UTF-8"));
		httpost.setEntity(byteArrayEntity);
		CloseableHttpResponse response = httpclient.execute(httpost);
		try {
			int status = response.getStatusLine().getStatusCode();
			if (status != 200) {
				throw new Exception("Unexpected response status: " + status);
			}
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity, "UTF-8");
		} finally {
			response.close();
		}
	} finally {
		httpclient.close();
	}
}
 
Example #6
Source File: EncodeDecodeHandlerTest.java    From light-4j with Apache License 2.0 6 votes vote down vote up
public void runTest(final String theMessage, String encoding) throws Exception {
    try (CloseableHttpClient client = HttpClientBuilder.create().disableContentCompression().build()){
        message = theMessage;
        HttpGet get = new HttpGet("http://localhost:8080/encode");
        get.setHeader(Headers.ACCEPT_ENCODING_STRING, encoding);
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Header[] header = result.getHeaders(Headers.CONTENT_ENCODING_STRING);
        Assert.assertEquals(encoding, header[0].getValue());
        byte[] body = HttpClientUtils.readRawResponse(result);

        HttpPost post = new HttpPost("http://localhost:8080/decode");
        post.setEntity(new ByteArrayEntity(body));
        post.addHeader(Headers.CONTENT_ENCODING_STRING, encoding);

        result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String sb = HttpClientUtils.readResponse(result);
        Assert.assertEquals(theMessage.length(), sb.length());
        Assert.assertEquals(theMessage, sb);
    }
}
 
Example #7
Source File: HttpUtils.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
/**
 * Post stream
 * 
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys, 
		byte[] body)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpPost request = new HttpPost(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (body != null) {
       	request.setEntity(new ByteArrayEntity(body));
       }

       return httpClient.execute(request);
   }
 
Example #8
Source File: RequestParamEndpointTest.java    From RoboZombie with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Test for a {@link Request} with a {@code byte[]} entity.</p>
 * 
 * @since 1.3.0
 */
@Test
public final void testPrimitiveByteArrayEntity() throws ParseException, IOException {
	
	Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
	
	String subpath = "/primitivebytearrayentity";
	byte[] bytes = new byte[] {1, 1, 1, 1, 1, 1, 1, 1};
	ByteArrayEntity bae = new ByteArrayEntity(bytes);
	
	stubFor(put(urlEqualTo(subpath))
			.willReturn(aResponse()
			.withStatus(200)));
	
	requestEndpoint.primitiveByteArrayEntity(bytes);
	
	verify(putRequestedFor(urlEqualTo(subpath))
		   .withRequestBody(equalTo(EntityUtils.toString(bae))));
}
 
Example #9
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Method posts request payload
 * 
 * @param request
 * @param payload
 * @return
 */
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload, HttpHost proxy) {
  HttpResponse response = null;
boolean ok = false;
int tryCount = 0;
while (!ok) {
  try {
    tryCount++;
    HttpClient httpclient = new DefaultHttpClient();
    if(proxy != null) {
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    request.setEntity(new ByteArrayEntity(payload));
    log(request);
    response = httpclient.execute(request);
    ok = true;
  } catch(IOException ioe) {
    if (tryCount <= retryCount) {
      ok = false;
    } else {
    throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
  }
  }
}
  return response;
}
 
Example #10
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Method posts request payload
 * 
 * @param request
 * @param payload
 * @return
 */
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload, HttpHost proxy) {
  HttpResponse response = null;
  boolean ok = false;
  int tryCount = 0;
  while (!ok) {
    try {
      tryCount++;
      HttpClient httpclient = new DefaultHttpClient();
      if(proxy != null) {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      request.setEntity(new ByteArrayEntity(payload));
      log(request);
      response = httpclient.execute(request);
      ok = true;
    } catch(IOException ioe) {
      if (tryCount <= retryCount) {
        ok = false;
      } else {
        throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
      }
    }
  }
  return response;
}
 
Example #11
Source File: HttpComponentsClientHttpRequest.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
	addHeaders(this.httpRequest, headers);

	if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
		HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest;
		HttpEntity requestEntity = new ByteArrayEntity(bufferedOutput);
		entityEnclosingRequest.setEntity(requestEntity);
	}
	HttpResponse httpResponse = this.httpClient.execute(this.httpRequest, this.httpContext);
	return new HttpComponentsClientHttpResponse(httpResponse);
}
 
Example #12
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Method posts request payload
 * 
 * @param request
 * @param payload
 * @return
 */
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload, HttpHost proxy) {
  HttpResponse response = null;
  boolean ok = false;
  int tryCount = 0;
  while (!ok) {
    try {
      tryCount++;
      HttpClient httpclient = new DefaultHttpClient();
      if(proxy != null) {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      request.setEntity(new ByteArrayEntity(payload));
      log(request);
      response = httpclient.execute(request);
      ok = true;
    } catch(IOException ioe) {
      if (tryCount <= retryCount) {
        ok = false;
      } else {
        throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
      }
    }
  }
  return response;
}
 
Example #13
Source File: CleanupTaskHelmIT.java    From nexus-repository-helm with Eclipse Public License 1.0 6 votes vote down vote up
private int deployArtifacts(final String... names) {
  try {
    HelmClient client = new HelmClient(clientBuilder().build(),
        clientContext(),
        resolveUrl(nexusUrl, format("/repository/%s/", repository.getName())).toURI()
    );

    for (String name : names) {
      assertThat(status(client.put(format("%s/%s", PKG_PATH, name), new ByteArrayEntity(getBytesFromTestData(name)))),
          is(OK));
    }

    return names.length;
  }
  catch (Exception e) {
    log.error("", e);
  }
  return 0;
}
 
Example #14
Source File: CaiPiaoHttpUtils.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * Post stream
 * 
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys, 
		byte[] body)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpPost request = new HttpPost(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (body != null) {
       	request.setEntity(new ByteArrayEntity(body));
       }

       return httpClient.execute(request);
   }
 
Example #15
Source File: CaiPiaoHttpUtils.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * Put stream
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPut(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys, 
		byte[] body)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpPut request = new HttpPut(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (body != null) {
       	request.setEntity(new ByteArrayEntity(body));
       }

       return httpClient.execute(request);
   }
 
Example #16
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Method posts request payload
 * 
 * @param request
 * @param payload
 * @return
 */
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload, HttpHost proxy) {
  HttpResponse response = null;
  boolean ok = false;
  int tryCount = 0;
  while (!ok) {
    try {
      tryCount++;
      HttpClient httpclient = new DefaultHttpClient();
      if(proxy != null) {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      request.setEntity(new ByteArrayEntity(payload));
      log(request);
      response = httpclient.execute(request);
      ok = true;
    } catch(IOException ioe) {
      if (tryCount <= retryCount) {
        ok = false;
      } else {
        throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
      }
    }
  }
  return response;
}
 
Example #17
Source File: HttpUtils.java    From frpMgr with MIT License 6 votes vote down vote up
/**
 * Post stream
 *
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method,
		Map<String, String> headers,
		Map<String, String> querys,
		byte[] body)
           throws Exception {
   	HttpClient httpClient = wrapClient(host);

   	HttpPost request = new HttpPost(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (body != null) {
       	request.setEntity(new ByteArrayEntity(body));
       }

       return httpClient.execute(request);
   }
 
Example #18
Source File: InfluxDBClient.java    From metrics with Apache License 2.0 6 votes vote down vote up
public void flush() throws IOException {
  if (byteBuffer.position() == 0) {
    return;
  }
  byteBuffer.flip();
  HttpPost httpPost = new HttpPost(this.dbUri);
  httpPost.setEntity(
      new ByteArrayEntity(byteBuffer.array(), 0, byteBuffer.limit(), ContentType.DEFAULT_TEXT));
  try {
    CloseableHttpResponse response = httpClient.execute(httpPost);
    EntityUtils.consumeQuietly(response.getEntity());
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode / 100 != 2) {
      throw new IOException(
          "InfluxDB write failed: " + statusCode + " " + response.getStatusLine()
              .getReasonPhrase());
    }
  } finally {
    // Always clear the buffer. But this will lead to data loss in case of non 2xx response (i.e write operation failed)
    // received from the InfluxDB server. Ideally non 2xx server response should be rare but revisit this part
    // if data loss occurs frequently.
    byteBuffer.clear();
  }
}
 
Example #19
Source File: HopServer.java    From hop with Apache License 2.0 6 votes vote down vote up
HttpPost buildSendXmlMethod( byte[] content, String service ) throws Exception {
  // Prepare HTTP put
  //
  String urlString = constructUrl( service );
  if ( log.isDebug() ) {
    log.logDebug( BaseMessages.getString( PKG, "HopServer.DEBUG_ConnectingTo", urlString ) );
  }
  HttpPost postMethod = new HttpPost( urlString );

  // Request content will be retrieved directly from the input stream
  //
  HttpEntity entity = new ByteArrayEntity( content );

  postMethod.setEntity( entity );
  postMethod.addHeader( new BasicHeader( "Content-Type", "text/xml;charset=" + Const.XML_ENCODING ) );

  return postMethod;
}
 
Example #20
Source File: CaiPiaoHttpUtils.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * Put stream
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPut(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys, 
		byte[] body)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpPut request = new HttpPut(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (body != null) {
       	request.setEntity(new ByteArrayEntity(body));
       }

       return httpClient.execute(request);
   }
 
Example #21
Source File: AliHttpUtils.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
/**
 * Post stream
 *
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method,
                                  Map<String, String> headers,
                                  Map<String, String> querys,
                                  byte[] body)
        throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (body != null) {
        request.setEntity(new ByteArrayEntity(body));
    }

    return httpClient.execute(request);
}
 
Example #22
Source File: PilosaClient.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public long[] translateKeys(Internal.TranslateKeysRequest request) throws IOException {
    String path = "/internal/translate/keys";
    ByteArrayEntity body = new ByteArrayEntity(request.toByteArray());
    CloseableHttpResponse response = clientExecute("POST", path, body, protobufHeaders, "Error while posting translateKey",
            ReturnClientResponse.RAW_RESPONSE, false);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream src = entity.getContent();
        Internal.TranslateKeysResponse translateKeysResponse = Internal.TranslateKeysResponse.parseFrom(src);
        List<Long> values = translateKeysResponse.getIDsList();
        long[] result = new long[values.size()];
        int i = 0;
        for (Long v : values) {
            result[i++] = v.longValue();
        }

        return result;

    }
    throw new PilosaException("Server returned empty response");
}
 
Example #23
Source File: PilosaClient.java    From java-pilosa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a field on the server using the given Field object.
 *
 * @param field field object
 * @throws HttpConflict if there already is a field with the given name
 * @see <a href="https://www.pilosa.com/docs/api-reference/#index-index-name-frame-frame-name">Pilosa API Reference: Field</a>
 */
public void createField(Field field) {
    Span span = this.tracer.buildSpan("Client.CreateField").start();
    try {
        String path = String.format("/index/%s/field/%s", field.getIndex().getName(), field.getName());
        String body = field.getOptions().toString();
        ByteArrayEntity data = new ByteArrayEntity(body.getBytes(StandardCharsets.UTF_8));
        clientExecute("POST", path, data, null, "Error while creating field");
    } finally {
        span.finish();
    }
}
 
Example #24
Source File: CreateGroup.java    From jam-collaboration-sample with Apache License 2.0 5 votes vote down vote up
/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PrintWriter out = response.getWriter();
	
	try {
		// Code to retrieve the Java SAP Cloud Platform Destination.
		// The SAP Cloud Platform Destination handles the SAML2OAuthBearer Assertion workflow.
		Context ctx = new InitialContext();
		HttpDestination destination = (HttpDestination)ctx.lookup("java:comp/env/sap_jam_odata");
		HttpClient client = destination.createHttpClient();
		
		//TODO URL
		String url = "/Groups";
		HttpPost jamRequest = new HttpPost( url );
		
		//For this code you need to retrieve the template ID of the template you want to use to create the group 
		String xmlBody = getCreateGroupRequest( "<add template ID", GroupTemplate.CUSTOM, "My new Group", DataFormat.JSON) ;
		HttpEntity entity = new ByteArrayEntity(xmlBody.getBytes("UTF-8"));
		jamRequest.setEntity(entity);
		jamRequest.setHeader("Content-Type", "application/xml");
		jamRequest.setHeader("Accept", "application/xml");
		
		HttpResponse jamResponse  = client.execute(jamRequest);
		HttpEntity responseEntity = jamResponse.getEntity();
		
		
		// Output to screen
		if ( responseEntity != null )
			out.println(EntityUtils.toString(responseEntity));
		else
			out.println( "There was a problem with the connection");
			out.println( jamResponse.toString() );
	} catch (Exception e) {
		response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
	}

	
}
 
Example #25
Source File: DicomWebStoreInstance.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void dicomWebStoreInstance(String dicomStoreName, String filePath)
    throws IOException, URISyntaxException {
  // String dicomStoreName =
  //    String.format(
  //        DICOM_NAME, "your-project-id", "your-region-id", "your-dataset-id", "your-dicom-id");
  // String filePath = "path/to/file.dcm";

  // Initialize the client, which will be used to interact with the service.
  CloudHealthcare client = createClient();

  HttpClient httpClient = HttpClients.createDefault();
  String uri = String.format("%sv1/%s/dicomWeb/studies", client.getRootUrl(), dicomStoreName);
  URIBuilder uriBuilder = new URIBuilder(uri).setParameter("access_token", getAccessToken());
  // Load the data from file representing the study.
  File f = new File(filePath);
  byte[] dicomBytes = Files.readAllBytes(Paths.get(filePath));
  ByteArrayEntity requestEntity = new ByteArrayEntity(dicomBytes);

  HttpUriRequest request =
      RequestBuilder.post(uriBuilder.build())
          .setEntity(requestEntity)
          .addHeader("Content-Type", "application/dicom")
          .build();

  // Execute the request and process the results.
  HttpResponse response = httpClient.execute(request);
  HttpEntity responseEntity = response.getEntity();
  if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
    System.err.print(
        String.format(
            "Exception storing DICOM instance: %s\n", response.getStatusLine().toString()));
    responseEntity.writeTo(System.err);
    throw new RuntimeException();
  }
  System.out.println("DICOM instance stored: ");
  responseEntity.writeTo(System.out);
}
 
Example #26
Source File: DS937BoxcarringTestCase.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public Object[] sendPOST(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter("http.socket.timeout", 120000);
    HttpPost httpPost = new HttpPost(endpoint);

    if (sessionID == null) {
        sessionID = "11";
    }
    headers.put("Cookie", sessionID);
    for (String headerType : headers.keySet()) {
        httpPost.setHeader(headerType, headers.get(headerType));
    }
    if (content != null) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPost.setHeader("Content-Type", "application/json");
        }
        httpPost.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPost);
    Header[] responseHeaders = httpResponse.getHeaders("Set-Cookie");
    if (responseHeaders != null && responseHeaders.length > 0) {
        sessionID = responseHeaders[0].getValue();
    }
    if (httpResponse.getEntity() != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
        return new Object[] { httpResponse.getStatusLine().getStatusCode(), response.toString() };
    } else {
        return new Object[] { httpResponse.getStatusLine().getStatusCode() };
    }
}
 
Example #27
Source File: HttpComponentsClientHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
	addHeaders(this.httpRequest, headers);

	if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
		HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest;
		HttpEntity requestEntity = new ByteArrayEntity(bufferedOutput);
		entityEnclosingRequest.setEntity(requestEntity);
	}
	HttpResponse httpResponse = this.httpClient.execute(this.httpRequest, this.httpContext);
	return new HttpComponentsClientHttpResponse(httpResponse);
}
 
Example #28
Source File: HttpDownloadHandler.java    From cetty with Apache License 2.0 5 votes vote down vote up
private RequestBuilder addFormParams(RequestBuilder requestBuilder, Seed seed) {
    if (seed.getRequestBody() != null) {
        ByteArrayEntity entity = new ByteArrayEntity(seed.getRequestBody().getBody());
        entity.setContentType(seed.getRequestBody().getContentType());
        requestBuilder.setEntity(entity);
    }
    return requestBuilder;
}
 
Example #29
Source File: HttpClientStack.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
        Request<?> request) throws AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
 
Example #30
Source File: GooglePlayAPI.java    From Raccoon with Apache License 2.0 5 votes vote down vote up
/**
 * Executes POST request and returns result as {@link ResponseWrapper}.
 * Content type can be specified for given byte array.
 */
private ResponseWrapper executePOSTRequest(String url, byte[] datapost, String contentType)
		throws IOException {

	HttpEntity httpEntity = executePost(url, new ByteArrayEntity(datapost),
			getHeaderParameters(this.getToken(), contentType));
	return GooglePlay.ResponseWrapper.parseFrom(httpEntity.getContent());

}