List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:jsonclient.JsonClient.java
private static String postToURL(String url, String message, DefaultHttpClient httpClient) throws IOException, IllegalStateException, UnsupportedEncodingException, RuntimeException { HttpPost postRequest = new HttpPost(url); StringEntity input = new StringEntity(message); input.setContentType("application/json"); postRequest.setEntity(input);/*from w w w . j a v a 2 s.c om*/ HttpResponse response = httpClient.execute(postRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; StringBuffer totalOutput = new StringBuffer(); //System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { //System.out.println(output); totalOutput.append(output); } return totalOutput.toString(); }
From source file:password.pwm.ws.client.rest.RestClientHelper.java
public static String makeOutboundRestWSCall(final PwmApplication pwmApplication, final Locale locale, final String url, final String jsonRequestBody) throws PwmOperationalException, PwmUnrecoverableException { final HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Accept", PwmConstants.AcceptValue.json.getHeaderValue()); if (locale != null) { httpPost.setHeader("Accept-Locale", locale.toString()); }//w ww .j a v a 2 s . com httpPost.setHeader("Content-Type", PwmConstants.ContentTypeValue.json.getHeaderValue()); final HttpResponse httpResponse; try { final StringEntity stringEntity = new StringEntity(jsonRequestBody); stringEntity.setContentType(PwmConstants.AcceptValue.json.getHeaderValue()); httpPost.setEntity(stringEntity); LOGGER.debug("beginning external rest call to: " + httpPost.toString() + ", body: " + jsonRequestBody); httpResponse = PwmHttpClient.getHttpClient(pwmApplication.getConfig()).execute(httpPost); final String responseBody = EntityUtils.toString(httpResponse.getEntity()); LOGGER.trace("external rest call returned: " + httpResponse.getStatusLine().toString() + ", body: " + responseBody); if (httpResponse.getStatusLine().getStatusCode() != 200) { final String errorMsg = "received non-200 response code (" + httpResponse.getStatusLine().getStatusCode() + ") when executing web-service"; LOGGER.error(errorMsg); throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg)); } return responseBody; } catch (IOException e) { final String errorMsg = "http response error while executing external rest call, error: " + e.getMessage(); LOGGER.error(errorMsg); throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg), e); } }
From source file:com.ibm.iot.iotspark.IoTPrediction.java
/** * Makes ReST call to the Predictive Analytics service with the given payload and responds with the predicted score. * /* www. j a v a 2 s . c om*/ * @param pURL * @param payload * @return * @throws ClientProtocolException * @throws IOException */ public static java.lang.String post(java.lang.String pURL, java.lang.String payload) throws ClientProtocolException, IOException { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(pURL); StringEntity input = new StringEntity(payload); input.setContentType("application/json"); post.setEntity(input); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder out = new StringBuilder(); java.lang.String line; while ((line = rd.readLine()) != null) { // System.out.println(line); out.append(line); } System.out.println(out.toString()); //Prints the string content read from input stream rd.close(); return out.toString(); }
From source file:com.fufang.httprequest.HttpPostBuild.java
public static String postBuildJson(String url, String params) throws UnsupportedEncodingException, ClientProtocolException, IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); String postResult = null;//from ww w . ja v a2s . c o m HttpPost httpPost = new HttpPost(url); System.out.println(" request " + httpPost.getRequestLine()); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000) .build(); httpPost.setConfig(requestConfig); StringEntity entity = new StringEntity(params.toString(), "UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); try { HttpResponse response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity responseEntity = response.getEntity(); postResult = EntityUtils.toString(responseEntity); } else { System.out.println("unexpected response status - " + status); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return postResult; }
From source file:info.bonjean.beluga.util.HTTPUtil.java
private static String jsonRequest(String urlStr, String data) throws CommunicationException { try {/* ww w .j a va 2s .c o m*/ StringEntity json = new StringEntity(data.toString()); json.setContentType("application/json"); HttpPost post = new HttpPost(urlStr); post.addHeader("Content-Type", "application/json"); post.setEntity(json); return BelugaHTTPClient.getInstance().requestPost(post); } catch (Exception e) { throw new CommunicationException("communicationProblem", e); } }
From source file:net.modelbased.proasense.storage.registry.RegisterSensorSSN.java
public static String postSensor(Sensor sensor) throws RequestErrorException { String content = JsonPrinter.sensorToJson(sensor); URI target;/*from w ww .j a va 2s .co m*/ try { target = new URI(sensor.getUri().toString() + SENSOR_PATH); } catch (URISyntaxException e1) { e1.printStackTrace(); throw new RequestErrorException(e1.getMessage()); } HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost(target); request.setHeader("Content-type", "application/json"); String response = null; try { StringEntity seContent = new StringEntity(content); seContent.setContentType("text/json"); request.setEntity(seContent); response = resolveResponse(client.execute(request)); } catch (Exception e) { throw new RequestErrorException(e.getMessage()); } return response; }
From source file:org.envirocar.app.network.RestClient.java
private static void put(String url, AsyncHttpResponseHandler handler, String contents, String user, String token) throws UnsupportedEncodingException { client.addHeader("Content-Type", "application/json"); setHeaders(user, token);/*ww w.j a v a 2s . c o m*/ StringEntity se = new StringEntity(contents); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); client.put(null, url, se, "application/json", handler); }
From source file:org.envirocar.app.network.RestClient.java
/** * @deprecated Use {@link DAOProvider#getSensorDAO()} / {@link SensorDAO#saveSensor(org.envirocar.app.model.Car, User)} * instead.//from w ww . j av a2 s. co m */ @Deprecated public static boolean createSensor(String jsonObj, String user, String token, AsyncHttpResponseHandler handler) { client.addHeader("Content-Type", "application/json"); setHeaders(user, token); try { StringEntity se = new StringEntity(jsonObj); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); client.post(null, ECApplication.BASE_URL + "/sensors", se, "application/json", handler); } catch (UnsupportedEncodingException e) { logger.warn(e.getMessage(), e); return false; } return true; }
From source file:se.vgregion.util.HTTPUtils.java
public static HttpResponse makePostXML(String url, String token, DefaultHttpClient client, String xml) throws Exception { HttpPost post = new HttpPost(url); StringEntity e = new StringEntity(xml, "utf-8"); e.setContentType("application/xml"); post.addHeader("X-TrackerToken", token); post.addHeader("Content-type", "application/xml"); post.setEntity(e);/*from w w w .j a v a 2 s . c om*/ return client.execute(post); }
From source file:com.ibm.xsp.xflow.activiti.util.HttpClientUtil.java
public static String post(String url, Cookie[] cookies, String content) { String body = null;//from w w w . j av a 2 s.co m try { StringBuffer buffer = new StringBuffer(); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(url); StringEntity input = new StringEntity(content); input.setContentType("application/json"); postRequest.setEntity(input); httpClient.setCookieStore(new BasicCookieStore()); String hostName = new URL(url).getHost(); String domain = hostName.substring(hostName.indexOf(".")); for (int i = 0; i < cookies.length; i++) { if (logger.isLoggable(Level.FINEST)) { logger.finest("Cookie:" + cookies[i].getName() + ":" + cookies[i].getValue() + ":" + cookies[i].getDomain() + ":" + cookies[i].getPath()); } BasicClientCookie cookie = new BasicClientCookie(cookies[i].getName(), cookies[i].getValue()); cookie.setVersion(0); cookie.setDomain(domain); cookie.setPath("/"); httpClient.getCookieStore().addCookie(cookie); } HttpResponse response = httpClient.execute(postRequest); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; if (logger.isLoggable(Level.FINEST)) { logger.finest("Output from Server .... \n"); } while ((output = br.readLine()) != null) { if (logger.isLoggable(Level.FINEST)) { logger.finest(output); } buffer.append(output); } httpClient.getConnectionManager().shutdown(); body = buffer.toString(); } catch (Exception e) { e.printStackTrace(); } return body; }