List of usage examples for org.apache.http.client.methods CloseableHttpResponse getAllHeaders
Header[] getAllHeaders();
From source file:it.greenvulcano.gvesb.virtual.gv_multipart.MultipartCallOperation.java
/** * /*from w ww. ja v a2s .c om*/ * @param gvBuffer * for transport data in GreenVulcano * @return the GVBuffer * * @see it.greenvulcano.gvesb.virtual.CallOperation#perform(it.greenvulcano.gvesb.buffer.GVBuffer) */ @Override public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException { StringBuffer callDump = new StringBuffer(); callDump.append("Performing RestCallOperation " + name).append("\n ").append("URL: ").append(url); if (isByteArray == true && gvBuffer.getObject() != null) { byte[] requestData; if (gvBuffer.getObject() instanceof byte[]) { requestData = (byte[]) gvBuffer.getObject(); } else { requestData = gvBuffer.getObject().toString().getBytes(); } callDump.append("\n ").append("Content-Length: " + requestData.length); ByteArrayBody byteArrayPart = new ByteArrayBody(requestData, contentType, fileName); multipartEntityBuilder.addPart(name, byteArrayPart); } else if (isFileProperty == true) { file = new File(gvBuffer.getProperty("DIR")); FileBody filePart = new FileBody(file, this.contentType, fileName); multipartEntityBuilder.addPart(filePartName, filePart); } try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); httpEntity = multipartEntityBuilder.build(); String responseString = EntityUtils.toString(httpEntity); httpPost.setEntity(multipartEntityBuilder.build()); for (Map.Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); httpPost.setHeader(key, value); } CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); Header[] responseHeaders = response.getAllHeaders(); Header contentType = responseEntity.getContentType(); InputStream responseStream = null; response.getStatusLine(); responseStream = responseEntity.getContent(); for (Header header : response.getAllHeaders()) { if (Objects.nonNull(header)) { gvBuffer.setProperty(header.getName(), header.getValue()); } } if (responseStream != null) { byte[] responseData = IOUtils.toByteArray(responseStream); String responseContentType = Optional .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse(""); if (responseContentType.startsWith("application/json") || responseContentType.startsWith("application/javascript")) { gvBuffer.setObject(new String(responseData, "UTF-8")); } else { gvBuffer.setObject(responseData); } } else { gvBuffer.setObject(null); } gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(response.getStatusLine())); gvBuffer.setProperty(RESPONSE_MESSAGE, String.valueOf(response)); callDump.append("\n " + gvBuffer); response.close(); logger.debug(callDump.toString()); } catch (Exception exc) { throw new CallException("GV_CALL_SERVICE_ERROR", new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() }, { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } }, exc); } return gvBuffer; }
From source file:com.restfiddle.handler.http.GenericHandler.java
private RfResponseDTO buildRfResponse(CloseableHttpResponse httpResponse) throws IOException { RfResponseDTO responseDTO = new RfResponseDTO(); String responseBody = ""; List<RfHeaderDTO> headers = new ArrayList<RfHeaderDTO>(); try {//from w w w . j a v a 2 s . c om logger.info("response status : " + httpResponse.getStatusLine()); responseDTO.setStatus(httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase()); HttpEntity responseEntity = httpResponse.getEntity(); Header[] responseHeaders = httpResponse.getAllHeaders(); RfHeaderDTO headerDTO = null; for (Header responseHeader : responseHeaders) { // logger.info("response header - name : " + responseHeader.getName() + " value : " + responseHeader.getValue()); headerDTO = new RfHeaderDTO(); headerDTO.setHeaderName(responseHeader.getName()); headerDTO.setHeaderValue(responseHeader.getValue()); headers.add(headerDTO); } Header contentType = responseEntity.getContentType(); logger.info("response contentType : " + contentType); // logger.info("content : " + EntityUtils.toString(responseEntity)); responseBody = EntityUtils.toString(responseEntity); EntityUtils.consume(responseEntity); } finally { httpResponse.close(); } responseDTO.setBody(responseBody); responseDTO.setHeaders(headers); return responseDTO; }
From source file:com.uploader.Vimeo.java
private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file) throws IOException { // try(CloseableHttpClient client = HttpClientBuilder.create().build()) { CloseableHttpClient client = HttpClientBuilder.create().build(); // CloseableHttpClient client = HttpClients.createDefault(); System.out.println("Building HTTP Client"); // try {/* w w w . j av a 2s . c om*/ // client = // } catch(Exception e) { // System.out.println("Err in CloseableHttpClient"); // } // System.out.println(client); HttpRequestBase request = null; String url = null; if (endpoint.startsWith("http")) { url = endpoint; } else { url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString(); } System.out.println(url); if (methodName.equals(HttpGet.METHOD_NAME)) { request = new HttpGet(url); } else if (methodName.equals(HttpPost.METHOD_NAME)) { request = new HttpPost(url); } else if (methodName.equals(HttpPut.METHOD_NAME)) { request = new HttpPut(url); } else if (methodName.equals(HttpDelete.METHOD_NAME)) { request = new HttpDelete(url); } else if (methodName.equals(HttpPatch.METHOD_NAME)) { request = new HttpPatch(url); } request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2"); request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString()); HttpEntity entity = null; if (params != null) { ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { postParameters.add(new BasicNameValuePair(key, params.get(key))); } entity = new UrlEncodedFormEntity(postParameters); } else { if (file != null) { entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA); } } if (entity != null) { if (request instanceof HttpPost) { ((HttpPost) request).setEntity(entity); } else if (request instanceof HttpPatch) { ((HttpPatch) request).setEntity(entity); } else if (request instanceof HttpPut) { ((HttpPut) request).setEntity(entity); } } CloseableHttpResponse response = client.execute(request); String responseAsString = null; int statusCode = response.getStatusLine().getStatusCode(); if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) { JSONObject out = new JSONObject(); for (Header header : response.getAllHeaders()) { try { out.put(header.getName(), header.getValue()); } catch (Exception e) { System.out.println("Err in out.put"); } } responseAsString = out.toString(); } else if (statusCode != 204) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); responseAsString = out.toString("UTF-8"); out.close(); } JSONObject json = null; try { json = new JSONObject(responseAsString); } catch (Exception e) { json = new JSONObject(); } VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode); response.close(); client.close(); return vimeoResponse; // } catch(IOException e) { // System.out.println("Error Building HTTP Client"); // } }
From source file:org.openhim.mediator.engine.connectors.HTTPConnector.java
private MediatorHTTPResponse buildResponseFromContent(MediatorHTTPRequest req, CloseableHttpResponse apacheResponse) throws IOException { String content = null;//w w w . ja v a 2s .c o m if (apacheResponse.getEntity() != null && apacheResponse.getEntity().getContent() != null) { content = IOUtils.toString(apacheResponse.getEntity().getContent()); } int status = apacheResponse.getStatusLine().getStatusCode(); Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (Header hdr : apacheResponse.getAllHeaders()) { headers.put(hdr.getName(), hdr.getValue()); } return new MediatorHTTPResponse(req, content, status, headers); }
From source file:org.openhim.mediator.e2e.E2EBase.java
protected E2EHTTPResponse executeHTTPRequest(String method, String path, String body, Map<String, String> headers, Map<String, String> params) throws URISyntaxException, IOException { URIBuilder builder = new URIBuilder().setScheme("http").setHost(testConfig.getServerHost()) .setPort(testConfig.getServerPort()).setPath(path); if (params != null) { Iterator<String> iter = params.keySet().iterator(); while (iter.hasNext()) { String param = iter.next(); builder.addParameter(param, params.get(param)); }//from w w w. j a v a2 s. c om } HttpUriRequest uriReq = buildUriRequest(method, body, builder.build()); if (headers != null) { Iterator<String> iter = headers.keySet().iterator(); while (iter.hasNext()) { String header = iter.next(); uriReq.addHeader(header, headers.get(header)); } } RequestConfig.Builder reqConf = RequestConfig.custom().setConnectTimeout(1000) .setConnectionRequestTimeout(1000); CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(reqConf.build()).build(); CloseableHttpResponse response = client.execute(uriReq); E2EHTTPResponse finalResponse = new E2EHTTPResponse(); if (response.getEntity() != null && response.getEntity().getContent() != null) { finalResponse.body = IOUtils.toString(response.getEntity().getContent()); } finalResponse.status = response.getStatusLine().getStatusCode(); for (Header hdr : response.getAllHeaders()) { finalResponse.headers.put(hdr.getName(), hdr.getValue()); } IOUtils.closeQuietly(response); return finalResponse; }
From source file:org.coding.git.api.CodingNetConnection.java
private ResponsePage createResponse(@NotNull JsonElement ret, @Nullable String path, @NotNull CloseableHttpResponse response) throws CodingNetOperationCanceledException { if (myAborted) throw new CodingNetOperationCanceledException(); return new ResponsePage(ret, path, response.getAllHeaders()); }
From source file:org.coding.git.api.CodingNetConnection.java
private ResponsePage createResponse(@NotNull CloseableHttpResponse response) throws CodingNetOperationCanceledException { if (myAborted) throw new CodingNetOperationCanceledException(); return new ResponsePage(null, null, response.getAllHeaders()); }
From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java
private Response execute(CloseableHttpClient http, ServerInfo serverInfo, HttpRequestBase request, MessageContext context) throws IOException { ensureCertsAreLoaded(context);/* ww w .j av a 2 s . c o m*/ CloseableHttpResponse response = http.execute(request, serverInfo.httpContext); if (response == null) { return Response.status(Response.Status.BAD_GATEWAY).build(); } Header[] responseHeaders = response.getAllHeaders(); ResponseBuilder builder = Response.status(response.getStatusLine().getStatusCode()); for (Header header : responseHeaders) { builder.header(header.getName(), header.getValue()); } String strReply = new String(EntityUtils.toByteArray(response.getEntity())); HttpServletRequest servletRequest = context.getHttpServletRequest(); StringBuffer entireRequestUrl = servletRequest.getRequestURL(); builder.entity(strReply.replaceAll(serverInfo.url.toExternalForm(), entireRequestUrl.substring(0, entireRequestUrl.indexOf(servletRequest.getPathInfo())) + "/" + serverInfo.name + "/")); return builder.build(); }