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 Project: product-ei   Author: wso2   File: ODataTestUtils.java    License: 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 Project: RoboZombie   Author: sahan   File: RequestParamEndpointTest.java    License: 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 #3
Source Project: blueflood   Author: rackerlabs   File: HttpHandlerIntegrationTest.java    License: 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 #4
Source Project: org.hl7.fhir.core   Author: hapifhir   File: ClientUtils.java    License: 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 #5
Source Project: org.hl7.fhir.core   Author: hapifhir   File: ClientUtils.java    License: 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 #6
Source Project: org.hl7.fhir.core   Author: hapifhir   File: ClientUtils.java    License: 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 #7
Source Project: org.hl7.fhir.core   Author: hapifhir   File: ClientUtils.java    License: 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 #8
Source Project: ZTuoExchange_framework   Author: sengeiou   File: CaiPiaoHttpUtils.java    License: 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 #9
Source Project: ZTuoExchange_framework   Author: sengeiou   File: CaiPiaoHttpUtils.java    License: 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 #10
Source Project: frpMgr   Author: Zo3i   File: HttpUtils.java    License: 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 #11
Source Project: metrics   Author: ultrabrew   File: InfluxDBClient.java    License: 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 #12
Source Project: hop   Author: project-hop   File: HopServer.java    License: 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 #13
Source Project: ZTuoExchange_framework   Author: homeyanmi   File: CaiPiaoHttpUtils.java    License: 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 #14
Source Project: charging_pile_cloud   Author: konglingyinxia   File: AliHttpUtils.java    License: 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 Project: dubbo-plus   Author: dubboclub   File: ClientInvoker.java    License: 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 #16
Source Project: nexus-repository-helm   Author: sonatype-nexus-community   File: CleanupTaskHelmIT.java    License: 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 #17
Source Project: spring4-understanding   Author: langtianya   File: HttpComponentsClientHttpRequest.java    License: 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 #18
Source Project: api-gateway-demo-sign-java   Author: aliyun   File: HttpUtils.java    License: 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 #19
Source Project: light-4j   Author: networknt   File: EncodeDecodeHandlerTest.java    License: 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 #20
Source Project: beam   Author: apache   File: InfluxDBPublisher.java    License: 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 #21
Source Project: tangyuan2   Author: xsonorg   File: HttpRpcClient.java    License: 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 #22
Source Project: java-pilosa   Author: pilosa   File: PilosaClient.java    License: 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 Project: micro-integrator   Author: wso2   File: DS937BoxcarringTestCase.java    License: 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 #24
Source Project: micro-integrator   Author: wso2   File: SPARQLServiceTestCase.java    License: 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();
    HttpPost httpPost = new HttpPost(endpoint);
    httpClient.getParams().setParameter("http.socket.timeout", 300000);
    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);
    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 #25
Source Project: micro-integrator   Author: wso2   File: ODataTestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Object[] sendPOST(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpoint);
    for (String headerType : headers.keySet()) {
        httpPost.setHeader(headerType, headers.get(headerType));
    }
    if (null != content) {
        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);
    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 #26
Source Project: olingo-odata4   Author: apache   File: TripPinServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateStream2() throws Exception {
  // treating update and create as same for now, as there is details about
  // how entity payload and media payload can be sent at same time in request's body
  String editUrl = baseURL + "/Airlines('AA')/Picture";
  HttpPut request = new HttpPut(editUrl);
  request.setEntity(new ByteArrayEntity("bytecontents".getBytes(), ContentType.APPLICATION_OCTET_STREAM));
  HttpResponse response = httpSend(request, 204);
  EntityUtils.consumeQuietly(response.getEntity());
}
 
Example #27
Source Project: AndroidProjects   Author: why168   File: OkApacheClientStack.java    License: MIT License 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 #28
Source Project: jus   Author: apptik   File: ApacheHttpStack.java    License: Apache License 2.0 5 votes vote down vote up
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
                                            Request<?> request) {
    byte[] body = request.getBody();
    if (body != null) {
        HttpEntity entity = new ByteArrayEntity(body);
        httpRequest.setEntity(entity);
    }
}
 
Example #29
Source Project: Repeat   Author: repeats   File: HttpServerUtilities.java    License: Apache License 2.0 5 votes vote down vote up
public static Void prepareResponse(HttpAsyncExchange exchange, int code, byte[] data) throws IOException {
	HttpResponse response = exchange.getResponse();
	response.setStatusCode(code);
	response.setEntity(new ByteArrayEntity(data));
	exchange.submitResponse(new BasicAsyncResponseProducer(response));
       return null;
}
 
Example #30
Source Project: micro-integrator   Author: wso2   File: ODataTenantUserTestCase.java    License: Apache License 2.0 5 votes vote down vote up
private static int sendPOST(String endpoint, String content, String acceptType) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpoint);
    httpPost.setHeader("Accept", acceptType);
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPost);
    return httpResponse.getStatusLine().getStatusCode();
}