List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:es.logongas.iothome.agent.http.Http.java
public Object post(URL url, Object data) { try {/*from w w w .j a v a2s . com*/ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(url.toURI()); StringEntity input = new StringEntity(objectMapper.writeValueAsString(data)); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest); String output = inputStreamToString(response.getEntity().getContent()); if (response.getStatusLine().getStatusCode() != 201) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + "\n" + output); } httpClient.getConnectionManager().shutdown(); return objectMapper.readValue(output, data.getClass()); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.wso2telco.gsma.authenticators.ussd.command.UssdCommand.java
/** * Post request./*from ww w . jav a2s. co m*/ * * @param url the url * @param requestStr the request str * @param operator the operator * @return the string * @throws IOException Signals that an I/O exception has occurred. */ private void postRequest(String url, String requestStr, String operator, BasicFutureCallback futureCallback) throws IOException { MobileConnectConfig.USSDConfig ussdConfig = DataHolder.getInstance().getMobileConnectConfig() .getUssdConfig(); final HttpPost postRequest = futureCallback.getPostRequest(); try { postRequest.setURI(new URI(url)); } catch (URISyntaxException ex) { log.error("Malformed URL - " + url, ex); } postRequest.addHeader("accept", "application/json"); postRequest.addHeader("Authorization", "Bearer " + ussdConfig.getAuthToken()); if (operator != null) { postRequest.addHeader("operator", operator); } StringEntity input = new StringEntity(requestStr); input.setContentType("application/json"); postRequest.setEntity(input); if (log.isDebugEnabled()) { log.debug("Posting data [ " + requestStr + " ] to url [ " + url + " ]"); } Util.sendAsyncRequest(postRequest, futureCallback); }
From source file:org.apache.stratos.kubernetes.client.rest.RestClient.java
/** * Handle http post request. Return String *//from w w w. j a va 2 s . co m * @param resourcePath This should be REST endpoint * @param jsonParamString The json string which should be executed from the post request * @return The HttpResponse * @throws Exception if any errors occur when executing the request */ public KubernetesResponse doPost(URI resourcePath, String jsonParamString) throws Exception { HttpPost postRequest = null; try { postRequest = new HttpPost(resourcePath); StringEntity input = new StringEntity(jsonParamString); input.setContentType("application/json"); postRequest.setEntity(input); return httpClient.execute(postRequest, new KubernetesResponseHandler()); } finally { releaseConnection(postRequest); } }
From source file:org.apache.stratos.kubernetes.client.rest.RestClient.java
public KubernetesResponse doPut(URI resourcePath, String jsonParamString) throws Exception { HttpPut putRequest = null;//from w w w . j a v a 2 s. c o m try { putRequest = new HttpPut(resourcePath); StringEntity input = new StringEntity(jsonParamString); input.setContentType("application/json"); putRequest.setEntity(input); return httpClient.execute(putRequest, new KubernetesResponseHandler()); } finally { releaseConnection(putRequest); } }
From source file:com.twosigma.cook.jobclient.JobClient.java
/** * Generate a HTTP POST request for a given uri and a JSON object. * * @param uri {@link URI} specifies the uri for the request. * @param params {@link JSONObject} specifies the parameters used in the HTTP POST request. * @return {@link HttpPost} request.//ww w . jav a 2s. c om * @throws URISyntaxException */ public static HttpPost makeHttpPost(URI uri, JSONObject params) { try { StringEntity input = new StringEntity(params.toString()); input.setContentType("application/json"); HttpPost request = new HttpPost(uri); request.setEntity(input); return request; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:com.strato.hidrive.api.connection.httpgateway.request.JSONPostRequest.java
protected HttpRequestBase createHttpRequest(String requestUri, HttpRequestParamsVisitor<?> visitor) throws UnsupportedEncodingException { HttpPost httpPost = new HttpPost(requestUri); String jsonString = ""; if (jsonObject != null) { jsonString = jsonObject.toString(); } else if (jsonArray != null) { jsonString = jsonArray.toString(); }//from w w w . ja v a 2s .co m StringEntity stringEntity = new StringEntity(jsonString, "UTF-8"); stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType(CONTENT_TYPE_APPLICATION_JSON); httpPost.setEntity(stringEntity); return httpPost; }
From source file:com.rackspacecloud.client.service_registry.clients.AuthClient.java
public synchronized boolean authenticate() throws Exception { // TODO: Move into separate keystone package HttpPost method = new HttpPost(this.authUrl + "/tokens"); String payload = "{\"auth\": {\"RAX-KSKEY:apiKeyCredentials\": {\"username\": \"" + this.username + "\", \"apiKey\": \"" + this.apiKey + "\"}}}"; StringEntity payloadEntity = new StringEntity(payload); payloadEntity.setContentType("application/json"); method.setHeader("User-Agent", Client.VERSION); method.setEntity(payloadEntity);/*from w w w . j a va 2 s. c om*/ logger.debug(String.format("Authenticating against auth API server: authUrl=%s, username=%s, apiKey=%s", this.authUrl, this.username, this.apiKey)); HttpResponse response = this.client.execute(method); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200 & statusCode != 203) { throw new Exception("Unexpected status code: " + statusCode); } HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); AuthData ad = AuthData.fromJson(data); this.authToken = ad.getAccess().getToken(); return true; }
From source file:org.ldp4j.apps.ldp4ro.servlets.Form2RDFServlet.java
/** * Upon receiving data from the RO creation form, * 1. parses the request to extract the form data * 2. converts them to RDF to generate a RO * 3. submit that RO to an LDP server that manages the RO *///from w w w . ja v a 2s .c o m protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestURL = request.getRequestURL().toString(); logger.debug("Received a POST request on '{}'", requestURL); Map<String, String[]> parameterMap = request.getParameterMap(); RoRDFModel ro = new RoRDFModel(parameterMap); Model model = ro.process(); ByteArrayOutputStream os = new ByteArrayOutputStream(); model.write(os, "TURTLE"); String roString = os.toString(); logger.debug("Form data is converted to RDF ... \n{}", roString); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost:8080/ldp4j/ldp-bc/"); //HttpPost post = new HttpPost("http://linkeddata4.dia.fi.upm.es:8088/ldp4j/ldp-bc/"); StringEntity body = new StringEntity(roString); body.setContentType("text/turtle"); post.setEntity(body); HttpResponse ldpResponse = httpclient.execute(post); try { int statusCode = ldpResponse.getStatusLine().getStatusCode(); logger.debug("LDP server responded with {} {}", statusCode, ldpResponse.getStatusLine().getReasonPhrase()); if (statusCode == 201 && ldpResponse.getFirstHeader("Location") != null) { String location = ldpResponse.getFirstHeader("Location").getValue(); logger.debug("URI of the newly created LDPR - {}", location); request.setAttribute("newURI", location); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/roCreated.jsp"); dispatcher.forward(request, response); } else { logger.error("An error occurred while creating the RO. {} {}", statusCode, ldpResponse.getStatusLine().getReasonPhrase()); } } finally { post.releaseConnection(); } }
From source file:org.envirocar.app.dao.remote.RemoteSensorDAO.java
private String registerSensor(String sensorString) throws IOException, NotConnectedException, UnauthorizedException, ResourceConflictException { HttpPost postRequest = new HttpPost(ECApplication.BASE_URL + "/sensors"); StringEntity se = new StringEntity(sensorString); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); postRequest.setEntity(se);/*from www .j a v a2 s . co m*/ HttpResponse response = super.executePayloadRequest(postRequest); Header[] h = response.getAllHeaders(); String location = ""; for (int i = 0; i < h.length; i++) { if (h[i].getName().equals("Location")) { location += h[i].getValue(); break; } } logger.info("location: " + location); return location.substring(location.lastIndexOf("/") + 1, location.length()); }
From source file:org.hydracache.server.httpd.handler.HttpGetMethodHandler.java
private void handleNotFound(HttpResponse response) { response.setStatusCode(HttpStatus.SC_NOT_FOUND); try {//from w ww . ja v a2 s . co m StringEntity body = new StringEntity("Data not found"); body.setContentType(PLAIN_TEXT_RESPONSE_CONTENT_TYPE); response.setEntity(body); } catch (UnsupportedEncodingException e) { log.error("Failed to generate response: ", e); } }