List of usage examples for org.apache.http.client.fluent Request addHeader
public Request addHeader(final String name, final String value)
From source file:gate.tagger.tagme.TaggerTagMeWS.java
protected String retrieveServerResponse(String text) { Request req = Request.Post(getTagMeServiceUrl().toString()); req.addHeader("Content-Type", "application/x-www-form-urlencoded"); req.bodyForm(//from www . j av a2s . com Form.form().add("text", text).add("gcube-token", getApiKey()).add("lang", getLanguageCode()) .add("tweet", getIsTweet().toString()).add("include_abstract", "false") .add("include_categories", "false").add("include_all_spots", "false") .add("long_text", getLongText().toString()).add("epsilon", getEpsilon().toString()).build(), Consts.UTF_8); logger.debug("Request is " + req); Response res = null; try { res = req.execute(); } catch (Exception ex) { throw new GateRuntimeException("Problem executing HTTP request: " + req, ex); } Content cont = null; try { cont = res.returnContent(); } catch (Exception ex) { throw new GateRuntimeException("Problem getting HTTP response content: " + res, ex); } String ret = cont.asString(); logger.debug("TagMe server response " + ret); return ret; }
From source file:photosharing.api.conx.UploadFileDefinition.java
/** * uploads a file to the IBM Connections Cloud using the Files Service * // w ww . j av a2 s. c om * @param bearer token * @param nonce * @param request * @param response */ public void uploadFile(String bearer, String nonce, HttpServletRequest request, HttpServletResponse response) { // Extracts from the Request Parameters String visibility = request.getParameter("visibility"); String title = request.getParameter("title"); String share = request.getParameter("share"); String tagsUnsplit = request.getParameter("q"); // Check for the Required Parameters if (visibility == null || title == null || title.isEmpty() || visibility.isEmpty()) { response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); } else { /* * Builds the URL Parameters */ StringBuilder builder = new StringBuilder(); builder.append("visibility=" + visibility + "&"); builder.append("title=" + title + "&"); // The Share parameters for the URL if (share != null && !share.isEmpty()) { builder.append("shared=true&"); builder.append("shareWith=" + share + "&"); } if (visibility.compareTo("private") == 0 && share == null) { builder.append("shared=false&"); } // Splits the TagString into Indvidual Tags // - Technically this API is limited to 3 tags at most. String[] tags = tagsUnsplit.split(","); for (String tag : tags) { logger.info("Tag-> " + tag); builder.append("tag=" + tag + "&"); } // Build the apiURL String apiUrl = getApiUrl() + "/myuserlibrary/feed?" + builder.toString(); //API Url logger.info(apiUrl); // Add the Headers String length = request.getHeader("X-Content-Length"); String contentType = request.getHeader("Content-Type"); String fileext = contentType.split("/")[1].split(";")[0]; String slug = title + "." + fileext; Request post = Request.Post(apiUrl); post.addHeader("Authorization", "Bearer " + bearer); post.addHeader("X-Update-Nonce", nonce); post.addHeader("Slug", slug); post.addHeader("Content-Type", contentType); logger.info("Authorization: Bearer " + bearer); logger.info("X-Update-Nonce: " + nonce); logger.info("Slug: " + slug); logger.info("Content-Type: " + contentType); try { // InputStream in = request.getInputStream(); Base64InputStream bis = new Base64InputStream(in); long len = Long.parseLong(length); InputStreamEntity entity = new InputStreamEntity(bis, len); post.body(entity); post.removeHeaders("Cookie"); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(post); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); logger.info("code is " + code); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Duplicate Item else if (code == HttpStatus.SC_CONFLICT) { response.setStatus(HttpStatus.SC_CONFLICT); } // Checks if Created else if (code == HttpStatus.SC_CREATED) { response.setStatus(HttpStatus.SC_OK); /** * Do Extra Processing Here to process the body */ InputStream inRes = hr.getEntity().getContent(); // Converts XML to JSON String String jsonString = org.apache.wink.json4j.utils.XML.toJson(inRes); JSONObject obj = new JSONObject(jsonString); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.append(obj.toString()); writer.close(); } else { // Catch All response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); InputStream inRes = hr.getEntity().getContent(); String out = IOUtils.toString(inRes); logger.info("Content: " + out); logger.info("Content Type of Response: " + response.getContentType()); Collection<String> coll = response.getHeaderNames(); Iterator<String> iter = coll.iterator(); while (iter.hasNext()) { String header = iter.next(); logger.info(header + " " + response.getHeader(header)); } } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("IOException " + e.toString()); e.printStackTrace(); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("SAXException " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("JSONException " + e.toString()); } } }
From source file:photosharing.api.conx.ProfileDefinition.java
/** * retrieves a profile based on the person's userid * /*from w w w.ja v a2 s .co m*/ * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void run(HttpServletRequest request, HttpServletResponse response) { /** * check if query is empty, send SC_PRECONDITION_FAILED - 412 */ String query = request.getParameter("uid"); if (query == null || query.isEmpty()) { response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); } /** * get the users bearer token */ HttpSession session = request.getSession(false); Object oData = session.getAttribute(OAuth20Handler.CREDENTIALS); if (oData == null) { logger.warning("OAuth20Data is null"); } OAuth20Data data = (OAuth20Data) oData; String bearer = data.getAccessToken(); try { /** * Example URL: * http://localhost:9080/photoSharing/api/profile?uid=self maps to * https://apps.collabservnext.com/profiles/atom/profileService.do * * and results in an id for the self user, this data is ideally cached on the client. */ if (query.compareTo("self") == 0) { String apiUrl = getApiUrlForServiceDoc(); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired - 403 if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized // SC_UNAUTHORIZED (401) else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Content is returned // OK (200) else if (code == HttpStatus.SC_OK) { InputStream in = hr.getEntity().getContent(); // Converts the XML to JSON // Alternatively, one can parse the XML using XPATH String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); logger.info("json string is " + jsonString); JSONObject jsonObj = new JSONObject(jsonString); JSONObject workspace = jsonObj.getJSONObject("service").getJSONObject("workspace") .getJSONObject("collection"); String id = workspace.getString("userid"); query = id; } else { JSONObject obj = new JSONObject(); obj.put("error", "unexpected content"); } } /** * The query should be cleansed before passing it to the backend * cleansing can incorporate checking that the id is a number * * example URL * http://localhost:9080/photoSharing/api/profile?uid=20131674 maps * to https * ://apps.collabservnext.com/profiles/atom/profile.do?userid * =20131674 * * example response {"img": * "https:\/\/apps.collabservnext.com\/profiles\/photo.do?key=fef1b5f3-586f-4470-ab0a-a9d4251fe1ec&lastMod=1443607729019","name":"P * a u l Demo","email":"demo@us.ibm.com"} * */ String apiUrl = getApiUrl(query); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired // SC_FORBIDDEN (403) if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized // SC_UNAUTHORIZED (401) else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Content is returned OK (200) else if (code == HttpStatus.SC_OK) { InputStream in = hr.getEntity().getContent(); // Converts the XML to JSON // Alternatively, one can parse the XML using XPATH String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); logger.info("json string is " + jsonString); JSONObject jsonObj = new JSONObject(jsonString); JSONObject entry = jsonObj.getJSONObject("feed").getJSONObject("entry"); logger.info("entry" + entry); // Check if the Entry exists for the given id if (entry != null) { // Start Building the Response String name = ""; String image = ""; String email = ""; JSONObject contributor = entry.getJSONObject("contributor"); name = contributor.getString("name"); email = contributor.getString("email"); JSONArray links = entry.getJSONArray("link"); // Scans through the links and finds the profile image // XPath is much more efficient boolean found = false; int idx = 0; int len = links.length(); while (!found && idx < len) { JSONObject link = links.getJSONObject(idx); String type = link.getString("type"); if (type != null && !type.isEmpty() && type.compareTo("image") == 0) { found = true; image = link.getString("href"); } idx++; } // Build the json to send back JSONObject profile = new JSONObject(); profile.put("name", name); profile.put("email", email); profile.put("img", image); profile.put("userid", query); // Write output streams ServletOutputStream out = response.getOutputStream(); profile.write(out); } else { // There is no Entry for the user with the id. response.setStatus(HttpStatus.SC_NOT_FOUND); PrintWriter out = response.getWriter(); out.println("User does not exist"); } } // Unexpected status else { JSONObject obj = new JSONObject(); obj.put("error", "unexpected content"); //Should serialize result response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("IOException " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("JSONException " + e.toString()); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("SAXException " + e.toString()); } }
From source file:us.nineworlds.plex.rest.PlexappFactory.java
/** * Given a resource's URL, read and return the serialized MediaContainer * @param resourceURL//w w w .ja v a 2s. c o m * @return * @throws MalformedURLException * @throws IOException * @throws Exception */ protected Request generateRequest(String url, boolean get) { Request r = null; if (get) r = Request.Get(url); else r = Request.Post(url); return r.addHeader("X-Plex-Client-Identifier", config.getClientIdentifier()) .addHeader("X-Plex-Product", config.getProduct()) .addHeader("X-Plex-Version", config.getProductVersion()) .addHeader("X-Plex-Device", config.getDevice()) .addHeader("X-Plex-Device-Name", config.getDeviceName()).addHeader("Cache-Control", "max-age=0"); }
From source file:me.vertretungsplan.parser.BaseParser.java
protected String httpGet(String url, String encoding, Map<String, String> headers) throws IOException, CredentialInvalidException { Request request = Request.Get(url).connectTimeout(15000).socketTimeout(15000); if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); }/* w ww . ja v a 2 s. c o m*/ } return executeRequest(encoding, request); }
From source file:me.vertretungsplan.parser.BaseParser.java
protected String httpPost(String url, String encoding, List<NameValuePair> formParams, Map<String, String> headers) throws IOException, CredentialInvalidException { Request request = Request.Post(url).bodyForm(formParams).connectTimeout(15000).socketTimeout(15000); if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); }/*from ww w . jav a 2s . co m*/ } return executeRequest(encoding, request); }
From source file:org.apache.sling.replication.transport.impl.HttpTransportHandler.java
private void deliverPackage(Executor executor, ReplicationPackage replicationPackage, ReplicationEndpoint replicationEndpoint) throws IOException { String type = replicationPackage.getType(); Request req = Request.Post(replicationEndpoint.getUri()).useExpectContinue(); if (useCustomHeaders) { String[] customizedHeaders = getCustomizedHeaders(customHeaders, replicationPackage.getAction(), replicationPackage.getPaths()); for (String header : customizedHeaders) { addHeader(req, header);// w w w. j a v a2s. com } } else { req.addHeader(ReplicationHeader.TYPE.toString(), type); } InputStream inputStream = null; Response response = null; try { if (useCustomBody) { String body = customBody == null ? "" : customBody; inputStream = new ByteArrayInputStream(body.getBytes()); } else { inputStream = replicationPackage.createInputStream(); } if (inputStream != null) { req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM); } response = executor.execute(req); } finally { IOUtils.closeQuietly(inputStream); } if (response != null) { Content content = response.returnContent(); if (log.isInfoEnabled()) { log.info("Replication content of type {} for {} delivered: {}", new Object[] { type, Arrays.toString(replicationPackage.getPaths()), content }); } } else { throw new IOException("response is empty"); } }
From source file:edu.jhuapl.dorset.http.apache.ApacheHttpClient.java
private void prepareRequest(Request apacheRequest) { if (getUserAgent() != null) { apacheRequest.userAgent(getUserAgent()); }/*from w w w. j a va2s. com*/ if (getConnectTimeout() != null) { apacheRequest.connectTimeout(getConnectTimeout()); } if (getReadTimeout() != null) { apacheRequest.socketTimeout(getReadTimeout()); } if (!requestHeaders.isEmpty()) { for (Map.Entry<String, String> entry : requestHeaders.entrySet()) { apacheRequest.addHeader(entry.getKey(), entry.getValue()); } } }
From source file:me.vertretungsplan.parser.BaseParser.java
@SuppressWarnings("SameParameterValue") protected String httpPost(String url, String encoding, String body, ContentType contentType, Map<String, String> headers) throws IOException, CredentialInvalidException { Request request = Request.Post(url).bodyString(body, contentType).connectTimeout(15000) .socketTimeout(15000);/*www . j a v a2 s . c o m*/ if (headers != null) { for (Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } } return executeRequest(encoding, request); }
From source file:us.nineworlds.plex.rest.PlexappFactory.java
/** * Given a resource's URL, read and return the serialized MediaContainer * @param resourceURL//from w ww .ja va 2 s. c om * @param get Is this a get request or post * @return * @throws MalformedURLException * @throws IOException * @throws Exception */ private MediaContainer serializeResource(String resourceURL, boolean get) throws MalformedURLException, IOException, Exception { System.out.println(resourceURL); Request request = generateRequest(resourceURL, get); if (!config.getPlexAuthenticationToken().isEmpty()) { //If we have an auth token, make sure to use it request = request.addHeader("X-Plex-Token", config.getPlexAuthenticationToken()); System.out.println("Token: " + config.getPlexAuthenticationToken()); } MediaContainer mediaContainer; mediaContainer = serializer.read(MediaContainer.class, request.execute().returnContent().asStream(), false); return mediaContainer; }