List of usage examples for org.apache.http.entity BasicHttpEntity setContentLength
public void setContentLength(long j)
From source file:com.lehealth.common.sdk.CCPRestSDK.java
/** * ???//from www.j ava 2 s. co m * * @param to * ? ??????????100 * @param templateId * ? ?Id * @param datas * ?? ???{??} * @return */ public JSONObject sendTemplateSMS(String to, String templateId, String[] datas, String domain, String appId, String sid, String token) { JSONObject errorInfo = this.accountValidate(domain, appId, sid, token); if (errorInfo != null) { return errorInfo; } if (StringUtils.isBlank(to) || StringUtils.isBlank(appId) || StringUtils.isBlank(templateId)) { throw new IllegalArgumentException("?:" + (StringUtils.isBlank(to) ? " ?? " : "") + (StringUtils.isBlank(templateId) ? " ?Id " : "") + ""); } String timestamp = DateFormatUtils.format(new Date(), Constant.dateFormat_yyyymmddhhmmss); String acountName = sid; String sig = sid + token + timestamp; String acountType = "Accounts"; String signature = DigestUtils.md5Hex(sig); String url = getBaseUrl(domain).append("/" + acountType + "/").append(acountName) .append("/" + TemplateSMS + "?sig=").append(signature).toString(); String src = acountName + ":" + timestamp; String auth = Base64.encodeBase64String(src.getBytes()); Map<String, String> header = new HashMap<String, String>(); header.put("Accept", "application/json"); header.put("Content-Type", "application/json;charset=utf-8"); header.put("Authorization", auth); JSONObject json = new JSONObject(); json.accumulate("appId", appId); json.accumulate("to", to); json.accumulate("templateId", templateId); if (datas != null) { JSONArray Jarray = new JSONArray(); for (String s : datas) { Jarray.add(s); } json.accumulate("datas", Jarray); } String requestBody = json.toString(); DefaultHttpClient httpclient = null; HttpPost postMethod = null; try { httpclient = new CcopHttpClient().registerSSL(domain, NumberUtils.toInt(SERVER_PORT), "TLS", "https"); postMethod = new HttpPost(url); if (header != null && !header.isEmpty()) { for (Entry<String, String> e : header.entrySet()) { postMethod.setHeader(e.getKey(), e.getValue()); } } postMethod.setConfig(PoolConnectionManager.requestConfig); BasicHttpEntity requestEntity = new BasicHttpEntity(); requestEntity.setContent(new ByteArrayInputStream(requestBody.getBytes("UTF-8"))); requestEntity.setContentLength(requestBody.getBytes("UTF-8").length); postMethod.setEntity(requestEntity); HttpResponse response = httpclient.execute(postMethod); HttpEntity entity = response.getEntity(); if (entity != null) { String result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); return JSONObject.fromObject(result); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (postMethod != null) { postMethod.releaseConnection(); } if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } return getMyError("999999", ""); }
From source file:com.cloud.cluster.ClusterServiceServletHttpHandler.java
private void writeResponse(HttpResponse response, int statusCode, String content) { if (content == null) { content = ""; }/*from w w w . j a v a 2 s. c o m*/ response.setStatusCode(statusCode); BasicHttpEntity body = new BasicHttpEntity(); body.setContentType("text/html; charset=UTF-8"); byte[] bodyData = content.getBytes(); body.setContent(new ByteArrayInputStream(bodyData)); body.setContentLength(bodyData.length); response.setEntity(body); }
From source file:com.aerofs.baseline.http.TestHttpRequestHandler.java
@Test public void shouldSuccessfullyPostAndReceiveResponseAfterMakingUnsuccessfulPost() throws Exception { // unsuccessful // how does this test work, you ask? // well, there's only one request processing // thread on the server so if that thread locks up waiting // for bytes that never come, even if the stream is closed // then the *second* request will time out. try {/* w w w . ja v a2 s .com*/ HttpPost post0 = new HttpPost( ServiceConfiguration.SERVICE_URL + "/" + Resources.BASIC_RESOURCE + "/data1"); post0.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN); BasicHttpEntity basic = new BasicHttpEntity(); basic.setChunked(true); basic.setContentLength(-1); basic.setContent(new InputStream() { private int counter = 0; @Override public int read() throws IOException { if (counter < (3 * 1024 * 1024)) { counter++; return 'a'; } else { throw new IOException("read failed"); } } }); post0.setEntity(basic); Future<HttpResponse> future0 = client.getClient().execute(post0, null); future0.get(); } catch (Exception e) { // noop } // successful HttpPost post = new HttpPost(ServiceConfiguration.SERVICE_URL + "/" + Resources.BASIC_RESOURCE + "/data1"); post.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN); post.setEntity(HttpUtils.writeStringToEntity("data2")); Future<HttpResponse> future = client.getClient().execute(post, null); HttpResponse response = future.get(10, TimeUnit.SECONDS); assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK)); assertThat(HttpUtils.readStreamToString(response.getEntity().getContent()), equalTo("data1-data2")); }
From source file:org.springframework.cloud.netflix.ribbon.apache.RibbonApacheHttpRequest.java
public HttpUriRequest toRequest(final RequestConfig requestConfig) { final RequestBuilder builder = RequestBuilder.create(this.context.getMethod()); builder.setUri(this.uri); for (final String name : this.context.getHeaders().keySet()) { final List<String> values = this.context.getHeaders().get(name); for (final String value : values) { builder.addHeader(name, value); }// ww w. jav a2 s. c o m } for (final String name : this.context.getParams().keySet()) { final List<String> values = this.context.getParams().get(name); for (final String value : values) { builder.addParameter(name, value); } } if (this.context.getRequestEntity() != null) { final BasicHttpEntity entity; entity = new BasicHttpEntity(); entity.setContent(this.context.getRequestEntity()); // if the entity contentLength isn't set, transfer-encoding will be set // to chunked in org.apache.http.protocol.RequestContent. See gh-1042 if (this.context.getContentLength() != null) { entity.setContentLength(this.context.getContentLength()); } else if ("GET".equals(this.context.getMethod())) { entity.setContentLength(0); } builder.setEntity(entity); } customize(this.context.getRequestCustomizers(), builder); builder.setConfig(requestConfig); return builder.build(); }
From source file:com.baasbox.android.HttpUrlConnectionClient.java
private HttpEntity asEntity(HttpURLConnection connection) { BasicHttpEntity entity = new BasicHttpEntity(); InputStream in;//from w w w. j av a 2 s.com try { in = connection.getInputStream(); } catch (IOException e) { in = connection.getErrorStream(); } entity.setContent(in); entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
From source file:com.lion328.xenonlauncher.minecraft.api.authentication.yggdrasil.YggdrasilMinecraftAuthenticator.java
private ResponseState sendRequest(String endpoint, String data) throws IOException, YggdrasilAPIException { URL url = new URL(serverURL, endpoint); // HttpURLConnection can only handle 2xx response code for headers // so it need to use HttpCore instead // maybe I could use an alternative like HttpClient // but for lightweight, I think is not a good idea BasicHttpEntity entity = new BasicHttpEntity(); byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); entity.setContent(new ByteArrayInputStream(dataBytes)); entity.setContentLength(dataBytes.length); HttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.getFile(), HttpVersion.HTTP_1_1);/*from w w w. ja v a 2s.c om*/ request.setHeader(new BasicHeader("Host", url.getHost())); request.setHeader(new BasicHeader("Content-Type", "application/json")); request.setHeader(new BasicHeader("Content-Length", Integer.toString(dataBytes.length))); request.setEntity(entity); Socket s; int port = url.getPort(); if (url.getProtocol().equals("https")) { if (port == -1) { port = 443; } s = SSLSocketFactory.getDefault().createSocket(url.getHost(), port); } else { if (port == -1) { port = 80; } s = new Socket(url.getHost(), port); } DefaultBHttpClientConnection connection = new DefaultBHttpClientConnection(8192); connection.bind(s); try { connection.sendRequestHeader(request); connection.sendRequestEntity(request); HttpResponse response = connection.receiveResponseHeader(); connection.receiveResponseEntity(response); if (!response.getFirstHeader("Content-Type").getValue().startsWith("application/json")) { throw new InvalidImplementationException("Invalid content type"); } InputStream stream = response.getEntity().getContent(); StringBuilder sb = new StringBuilder(); int b; while ((b = stream.read()) != -1) { sb.append((char) b); } return new ResponseState(response.getStatusLine().getStatusCode(), sb.toString()); } catch (HttpException e) { throw new IOException(e); } }
From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java
/** * Triggered when the connection is ready to send an HTTP request. * * @see NHttpClientConnection//from ww w . jav a2s. c o m * * @param conn HTTP connection that is ready to send an HTTP request */ public void requestReady(final NHttpClientConnection conn) { System.out.println(conn + " [proxy->origin] request ready"); HttpContext context = conn.getContext(); ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB); // TODO: change it to ReentrantLock synchronized (proxyTask) { if (requestReadyValidateConnectionState(proxyTask)) return; HttpRequest request = proxyTask.getRequest(); if (request == null) { throw new IllegalStateException("HTTP request is null"); } requestReadyCleanUpHeaders(request); HttpHost targetHost = proxyTask.getTarget(); try { request.setParams(new DefaultedHttpParams(request.getParams(), this.params)); // Pre-process HTTP request context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost); this.httpProcessor.process(request, context); // and send it to the origin server Request originalRequest = proxyTask.getOriginalRequest(); int length = originalRequest.getContentLength(); if (length > 0) { BasicHttpEntity httpEntity = new BasicHttpEntity(); httpEntity.setContentLength(originalRequest.getContentLengthLong()); /* httpEntity.setContent(((InternalInputBuffer) originalRequest.getInputBuffer()).getInputStream()); ((BasicHttpEntityEnclosingRequest) request).setEntity(httpEntity); */ } conn.submitRequest(request); // Update connection state proxyTask.setOriginState(ConnState.REQUEST_SENT); System.out.println(conn + " [proxy->origin] >> " + request.getRequestLine().toString()); } catch (IOException ex) { shutdownConnection(conn); } catch (HttpException ex) { shutdownConnection(conn); } } }
From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java
/** * HTTP????,??/*w w w . ja va 2s . co m*/ * @param connection * @return HttpEntity */ private HttpEntity entityFromURLConnwction(HttpURLConnection connection) { BasicHttpEntity entity = new BasicHttpEntity(); InputStream inputStream = null; try { inputStream = connection.getInputStream(); } catch (IOException e) { e.printStackTrace(); inputStream = connection.getErrorStream(); } // TODO : GZIP entity.setContent(inputStream); entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
From source file:org.geoserver.wms.map.MockHttpClientConnectionManager.java
@Override public ConnectionRequest requestConnection(HttpRoute arg0, Object arg1) { return new ConnectionRequest() { @Override/*from ww w.j a v a 2s.com*/ public boolean cancel() { return false; } @Override public HttpClientConnection get(long arg0, TimeUnit arg1) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException { connections++; return new HttpClientConnection() { @Override public void shutdown() throws IOException { } @Override public void setSocketTimeout(int arg0) { } @Override public boolean isStale() { return false; } @Override public boolean isOpen() { return true; } @Override public int getSocketTimeout() { return 0; } @Override public HttpConnectionMetrics getMetrics() { return null; } @Override public void close() throws IOException { } @Override public void sendRequestHeader(HttpRequest arg0) throws HttpException, IOException { } @Override public void sendRequestEntity(HttpEntityEnclosingRequest arg0) throws HttpException, IOException { } @Override public HttpResponse receiveResponseHeader() throws HttpException, IOException { return new HttpResponse() { List<Header> headers = new ArrayList<Header>(); @Override public void addHeader(Header arg0) { } @Override public void addHeader(String arg0, String arg1) { } @Override public boolean containsHeader(String arg0) { return false; } @Override public Header[] getAllHeaders() { return headers.toArray(new Header[] {}); } public Header getHeader(String header) { if ("transfer-encoding".equalsIgnoreCase(header)) { return new BasicHeader(header, "identity"); } if ("date".equalsIgnoreCase(header)) { return new BasicHeader(header, dateFormat.format(new GregorianCalendar().getTime())); } if ("cache-control".equalsIgnoreCase(header)) { return new BasicHeader(header, enableCache ? "public" : "no-cache"); } if ("content-length".equalsIgnoreCase(header)) { return new BasicHeader(header, response.length() + ""); } if ("content-encoding".equalsIgnoreCase(header)) { return new BasicHeader(header, "identity"); } if ("age".equalsIgnoreCase(header)) { return new BasicHeader(header, "0"); } if ("expires".equalsIgnoreCase(header) && enableCache) { GregorianCalendar expires = new GregorianCalendar(); expires.add(GregorianCalendar.MINUTE, 30); return new BasicHeader(header, dateFormat.format(expires.getTime())); } return new BasicHeader(header, ""); } @Override public Header getFirstHeader(String header) { Header value = getHeader(header); headers.add(value); return value; } @Override public Header[] getHeaders(String header) { return new Header[] { getFirstHeader(header) }; } @Override public Header getLastHeader(String header) { return new BasicHeader(header, ""); } @Override public HttpParams getParams() { // TODO Auto-generated method stub return null; } @Override public ProtocolVersion getProtocolVersion() { return HttpVersion.HTTP_1_1; } @Override public HeaderIterator headerIterator() { return new BasicHeaderIterator(headers.toArray(new Header[] {}), "mock"); } @Override public HeaderIterator headerIterator(String header) { return new BasicHeaderIterator(headers.toArray(new Header[] {}), "mock"); } @Override public void removeHeader(Header arg0) { } @Override public void removeHeaders(String arg0) { } @Override public void setHeader(Header arg0) { } @Override public void setHeader(String arg0, String arg1) { } @Override public void setHeaders(Header[] arg0) { } @Override public void setParams(HttpParams arg0) { } @Override public HttpEntity getEntity() { BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentLength(response.length()); entity.setContent( new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8))); return entity; } @Override public Locale getLocale() { return Locale.ENGLISH; } @Override public StatusLine getStatusLine() { return new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"); } @Override public void setEntity(HttpEntity arg0) { } @Override public void setLocale(Locale arg0) { } @Override public void setReasonPhrase(String arg0) throws IllegalStateException { } @Override public void setStatusCode(int arg0) throws IllegalStateException { } @Override public void setStatusLine(StatusLine arg0) { } @Override public void setStatusLine(ProtocolVersion arg0, int arg1) { } @Override public void setStatusLine(ProtocolVersion arg0, int arg1, String arg2) { } }; } @Override public void receiveResponseEntity(HttpResponse arg0) throws HttpException, IOException { } @Override public boolean isResponseAvailable(int arg0) throws IOException { return true; } @Override public void flush() throws IOException { } }; } }; }