下面列出了怎么用org.apache.http.entity.ByteArrayEntity的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
/**
* <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))));
}
@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
}
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
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();
}
}
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;
}
/**
* 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);
}
/**
* 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);
}
@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();
}
}
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;
}
@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);
}
/**
* 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);
}
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);
}
}
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);
}
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();
}
}
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");
}
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() };
}
}
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() };
}
}
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() };
}
}
@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());
}
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);
}
}
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest,
Request<?> request) {
byte[] body = request.getBody();
if (body != null) {
HttpEntity entity = new ByteArrayEntity(body);
httpRequest.setEntity(entity);
}
}
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;
}
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();
}