List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr)
From source file:org.apache.edgent.test.connectors.http.HttpTest.java
@Test public void testPost() throws Exception { DirectProvider ep = new DirectProvider(); Topology topology = ep.newTopology(); String url = "http://httpbin.org/post"; TStream<String> stream = topology.strings(url); TStream<String> rc = HttpStreams.<String, String>requestsWithBody(stream, HttpClients::noAuthentication, t -> HttpPost.METHOD_NAME, t -> t, t -> new ByteArrayEntity(t.getBytes()), HttpResponders.inputOn200()); Tester tester = topology.getTester(); Condition<List<String>> endCondition = tester.streamContents(rc, url); tester.complete(ep, new JsonObject(), endCondition, 10, TimeUnit.SECONDS); assertTrue(endCondition.valid());//from w ww. j av a2s .c om }
From source file:org.wso2.cdm.agent.utils.HTTPConnectorUtils.java
public static Map<String, String> postToServer(Context context, String url, Map<String, String> params) { // Create a new HttpClient and Post Header Map<String, String> response_params = new HashMap<String, String>(); HttpClient httpclient = getCertifiedHttpClient(context); StringBuilder bodyBuilder = new StringBuilder(); if (params != null) { Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); }//from ww w .j a va2 s .c o m } } String body = bodyBuilder.toString(); byte[] postData = body.getBytes(); HttpPost httppost = new HttpPost(url); httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); httppost.setHeader("Accept", "*/*"); httppost.setHeader("User-Agent", "Mozilla/5.0 ( compatible ), Android"); try { // Add your data httppost.setEntity(new ByteArrayEntity(postData)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); response_params.put("response", getResponseBody(response)); response_params.put("status", String.valueOf(response.getStatusLine().getStatusCode())); return response_params; } catch (ClientProtocolException e) { Map<String, String> reply = new HashMap<String, String>(); reply.put("status", CommonUtilities.INTERNAL_SERVER_ERROR); return reply; } catch (IOException e) { Map<String, String> reply = new HashMap<String, String>(); reply.put("status", CommonUtilities.INTERNAL_SERVER_ERROR); return reply; } }
From source file:com.kubeiwu.commontool.khttp.toolbox.HttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *//* ww w. j a va2 s . c o m*/ /* protected */static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:org.b3log.latke.urlfetch.bae.BAEURLFetchService.java
@Override public HTTPResponse fetch(final HTTPRequest request) throws IOException { final HttpClient httpClient = new DefaultHttpClient(); final URL url = request.getURL(); final HTTPRequestMethod requestMethod = request.getRequestMethod(); HttpUriRequest httpUriRequest = null; try {/*from w ww. j av a 2s .co m*/ final byte[] payload = request.getPayload(); switch (requestMethod) { case GET: final HttpGet httpGet = new HttpGet(url.toURI()); // FIXME: GET with payload httpUriRequest = httpGet; break; case DELETE: httpUriRequest = new HttpDelete(url.toURI()); break; case HEAD: httpUriRequest = new HttpHead(url.toURI()); break; case POST: final HttpPost httpPost = new HttpPost(url.toURI()); if (null != payload) { httpPost.setEntity(new ByteArrayEntity(payload)); } httpUriRequest = httpPost; break; case PUT: final HttpPut httpPut = new HttpPut(url.toURI()); if (null != payload) { httpPut.setEntity(new ByteArrayEntity(payload)); } httpUriRequest = httpPut; break; default: throw new RuntimeException("Unsupported HTTP request method[" + requestMethod.name() + "]"); } } catch (final Exception e) { LOGGER.log(Level.SEVERE, "URL fetch failed", e); throw new IOException("URL fetch failed [msg=" + e.getMessage() + ']'); } final List<HTTPHeader> headers = request.getHeaders(); for (final HTTPHeader header : headers) { httpUriRequest.addHeader(header.getName(), header.getValue()); } final HttpResponse res = httpClient.execute(httpUriRequest); final HTTPResponse ret = new HTTPResponse(); ret.setContent(EntityUtils.toByteArray(res.getEntity())); ret.setResponseCode(res.getStatusLine().getStatusCode()); return ret; }
From source file:org.springframework.ws.transport.http.HttpComponentsConnection.java
@Override protected void onSendAfterWrite(WebServiceMessage message) throws IOException { httpPost.setEntity(new ByteArrayEntity(requestBuffer.toByteArray())); requestBuffer = null;/* w w w . jav a 2s .c om*/ if (httpContext != null) { httpResponse = httpClient.execute(httpPost, httpContext); } else { httpResponse = httpClient.execute(httpPost); } }
From source file:org.surfnet.oaaas.selenium.AuthorizationCodeRequestHandler.java
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { final String uri = request.getRequestLine().getUri(); Map<String, String> params = getParamsFromUri(uri); String authorizationCode = params.get("code"); authorizationResponseState = params.get("state"); LOG.debug("URL: {}, state: {}", uri, authorizationResponseState); final HttpPost tokenRequest = new HttpPost(oauthServerBaseUrl + "/oauth2/token"); String postBody = getPostBody(authorizationCode, grantType); tokenRequest.setEntity(new ByteArrayEntity(postBody.getBytes())); tokenRequest.addHeader("Authorization", AuthorizationCodeTestIT.authorizationBasic(clientId, secret)); tokenRequest.addHeader("Content-Type", "application/x-www-form-urlencoded"); HttpResponse tokenHttpResponse = new DefaultHttpClient().execute(tokenRequest); final InputStream responseContent = tokenHttpResponse.getEntity().getContent(); String responseAsString = new Scanner(responseContent).useDelimiter("\\A").next(); responseContent.close();// www . j ava 2s . c o m tokenResponse = responseAsString; }
From source file:cn.bidaround.ytcore.util.HttpClientStack.java
/** * Creates the appropriate subclass of HttpUriRequest for passed in request. *//*from w ww . j ava2 s.co m*/ @SuppressWarnings("deprecation") /* protected */ static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders) throws AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: { // This is the deprecated way that needs to be handled for backwards compatibility. // If the request's post body is null, then the assumption is that the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); HttpEntity entity; entity = new ByteArrayEntity(postBody); postRequest.setEntity(entity); return postRequest; } else { return new HttpGet(request.getUrl()); } } case Method.GET: return new HttpGet(request.getUrl()); case Method.DELETE: return new HttpDelete(request.getUrl()); case Method.POST: { HttpPost postRequest = new HttpPost(request.getUrl()); postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(postRequest, request); return postRequest; } case Method.PUT: { HttpPut putRequest = new HttpPut(request.getUrl()); putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(putRequest, request); return putRequest; } case Method.HEAD: return new HttpHead(request.getUrl()); case Method.OPTIONS: return new HttpOptions(request.getUrl()); case Method.TRACE: return new HttpTrace(request.getUrl()); case Method.PATCH: { HttpPatch patchRequest = new HttpPatch(request.getUrl()); patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType()); setEntityIfNonEmptyBody(patchRequest, request); return patchRequest; } default: throw new IllegalStateException("Unknown request method."); } }
From source file:org.apache.sling.distribution.it.DistributionUtils.java
private static String assertPostResource(SlingInstance slingInstance, int status, String path, byte[] bytes) throws IOException { Request request = slingInstance.getRequestBuilder().buildPostRequest(path); if (bytes != null) { ByteArrayEntity entity = new ByteArrayEntity(bytes); request.withEntity(entity);// w w w .j a va 2 s . c o m } return slingInstance.getRequestExecutor().execute( request.withCredentials(slingInstance.getServerUsername(), slingInstance.getServerPassword())) .assertStatus(status).getContent(); }
From source file:com.subgraph.vega.internal.http.requests.RepeatableStreamingEntity.java
private void setActiveByteArrayEntity(byte[] content) { ByteArrayEntity entity = new ByteArrayEntity(content); isStreaming = false;/* w w w. j a v a 2 s .co m*/ length = content.length; bufferEntity = entity; input = null; }
From source file:org.surfnet.oaaas.selenium.RefreshTokenTestIT.java
@Test public void refreshCode() throws Exception { /*//w w w . ja v a 2 s . co m * First do a normal authorization and obtain a AccessToken (with refreshToken) */ String accessTokenRedirectUri = startAuthorizationCallbackServer(clientId, secret); restartBrowserSession(); WebDriver webdriver = getWebDriver(); String responseType = "code"; String url = String.format("%s/oauth2/authorize?response_type=%s&client_id=%s&scope=read&redirect_uri=%s", baseUrl(), responseType, clientId, accessTokenRedirectUri); webdriver.get(url); /* * Consent is not necessary for this Client */ login(webdriver, false); // get token response System.out.println("Getting response"); String tokenResponse = getAuthorizationCodeRequestHandler().getTokenResponseBlocking(); System.out.println("Got response"); AccessTokenResponse accessTokenResponse = getMapper().readValue(tokenResponse, AccessTokenResponse.class); assertTrue(StringUtils.isNotBlank(accessTokenResponse.getAccessToken())); assertTrue(StringUtils.isNotBlank(accessTokenResponse.getRefreshToken())); assertTrue(StringUtils.isNotBlank(accessTokenResponse.getScope())); assertTrue(StringUtils.isNotBlank(accessTokenResponse.getTokenType())); assertTrue(accessTokenResponse.getExpiresIn() > 0); String tokenUrl = String.format("%s/oauth2/token", baseUrl()); final HttpPost tokenRequest = new HttpPost(tokenUrl); /* * Now make a request for a new AccessToken based on the refreshToken */ String postBody = String.format("grant_type=%s&refresh_token=%s&state=%s", OAuth2Validator.GRANT_TYPE_REFRESH_TOKEN, accessTokenResponse.getRefreshToken(), "dummy"); tokenRequest.setEntity(new ByteArrayEntity(postBody.getBytes())); tokenRequest.addHeader("Authorization", AuthorizationCodeTestIT.authorizationBasic(clientId, secret)); tokenRequest.addHeader("Content-Type", "application/x-www-form-urlencoded"); HttpResponse tokenHttpResponse = new DefaultHttpClient().execute(tokenRequest); final InputStream responseContent = tokenHttpResponse.getEntity().getContent(); String responseAsString = IOUtils.toString(responseContent); AccessTokenResponse refreshTokenResponse = getMapper().readValue(responseAsString, AccessTokenResponse.class); assertTrue(StringUtils.isNotBlank(refreshTokenResponse.getAccessToken())); assertTrue(StringUtils.isNotBlank(refreshTokenResponse.getRefreshToken())); assertTrue(StringUtils.isNotBlank(refreshTokenResponse.getScope())); assertTrue(StringUtils.isNotBlank(refreshTokenResponse.getTokenType())); assertTrue(accessTokenResponse.getExpiresIn() > 0); assertNotSame(refreshTokenResponse.getAccessToken(), accessTokenResponse.getAccessToken()); assertNotSame(refreshTokenResponse.getRefreshToken(), accessTokenResponse.getRefreshToken()); assertEquals(refreshTokenResponse.getScope(), accessTokenResponse.getScope()); assertEquals(refreshTokenResponse.getExpiresIn(), accessTokenResponse.getExpiresIn()); }