List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:com.vsct.dt.hesperides.feedback.FeedbacksAggregate.java
@Override public void sendFeedbackToHipchat(final User user, final FeedbackJson template) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Feedback from " + user.getUsername() + " to hipchat room\n" + template.toJsonString()); }// w w w.j av a 2 s .c o m final String imageData = template.getFeedback().getImg().split(",")[1]; final String imageName = String.format("feedback_%s.png", template.getFeedback().getTimestamp()); try { final String applicationPath; final Iterator<Map.Entry<String, String>> itOverride = assetsConfiguration.getOverrides().iterator(); if (itOverride.hasNext()) { applicationPath = itOverride.next().getValue(); } else { throw new HesperidesException("Could not create Feedback: asserts configuration not valid"); } LOGGER.debug("Server path : {}", applicationPath); writeImage(getServerPathImageName(applicationPath, imageName), imageData); CloseableHttpClient httpClient = getHttpClient(); HttpPost postRequest = new HttpPost(getHipchatUrl()); StringEntity input = new StringEntity(getHipchatMessageBody(template, imageName, user)); input.setContentType("application/json"); postRequest.setEntity(input); // LOG if (LOGGER.isDebugEnabled()) { LOGGER.debug("------------- Post send Hipchat request ------------------------------------------"); LOGGER.debug(postRequest.toString()); LOGGER.debug("------------- Post send Hipchat content request ---------------------------------"); LOGGER.debug(getStringContent(postRequest.getEntity())); } HttpResponse postResponse = httpClient.execute(postRequest); // LOG LOGGER.debug("------------- Post send Hipchat response ------------------------------------------"); LOGGER.debug(postResponse.toString()); if (postResponse.getStatusLine().getStatusCode() != 204) { throw new RuntimeException( "Failed : HTTP error code : " + postResponse.getStatusLine().getStatusCode()); } } catch (IOException e) { e.printStackTrace(); } }
From source file:functionaltests.AbstractRestFuncTestCase.java
private String getSession(String schedulerUrl, String username, String password) throws Exception { String resourceUrl = getResourceUrl("login"); HttpPost httpPost = new HttpPost(resourceUrl); StringBuilder buffer = new StringBuilder(); buffer.append("username=").append(username).append("&password=").append(password); StringEntity entity = new StringEntity(buffer.toString()); entity.setContentType(MediaType.APPLICATION_FORM_URLENCODED); httpPost.setEntity(entity);/*from w ww . j a va2 s . c om*/ HttpResponse response = HttpClientBuilder.create().build().execute(httpPost); String responseContent = EntityUtils.toString(response.getEntity()); if (STATUS_OK != getStatusCode(response)) { throw new RuntimeException(String.format("Authentication error: %n%s", responseContent)); } else { return responseContent; } }
From source file:com.meltmedia.cadmium.blackbox.test.ApiRequest.java
private void addPostBody(HttpUriRequest request) throws Exception { String postContent = null;/*from w ww.j a v a2s . c om*/ if (postBody != null) { if (postBody instanceof String) { postContent = (String) postBody; } else if (postBody instanceof Map && (postContentType == null || !postContentType.equals("application/json"))) { Map<?, ?> postBodyMap = (Map<?, ?>) postBody; if (!postBodyMap.isEmpty()) { postContent = ""; for (Object key : postBodyMap.keySet()) { Object value = postBodyMap.get(key); if (value instanceof Collection) { Collection<?> values = (Collection<?>) value; for (Object val : values) { if (postContent.length() > 0) { postContent += "&"; } postContent += URLEncoder.encode(key.toString(), "UTF-8"); postContent += "=" + URLEncoder.encode(val.toString(), "UTF-8"); } } else { if (postContent.length() > 0) { postContent += "&"; } postContent += URLEncoder.encode(key.toString(), "UTF-8"); postContent += "=" + URLEncoder.encode(value.toString(), "UTF-8"); } } } if (postContentType == null) { postContentType = "application/x-www-form-urlencoded"; } } else { postContent = new Gson().toJson(postBody); } if (postContent != null && request instanceof HttpEntityEnclosingRequestBase) { System.out.println("Posting body: " + postContent); HttpEntityEnclosingRequestBase entityBasedRequest = (HttpEntityEnclosingRequestBase) request; StringEntity entity = new StringEntity(postContent); entityBasedRequest.setEntity(entity); if (postContentType != null) { entity.setContentType(postContentType); } } } }
From source file:org.ttrssreader.net.deprecated.ApacheJSONConnector.java
protected InputStream doRequest(Map<String, String> params) { HttpPost post = new HttpPost(); try {/*from w w w. j a v a 2 s . c o m*/ if (sessionId != null) params.put(SID, sessionId); // Set Address post.setURI(Controller.getInstance().uri()); post.addHeader("Accept-Encoding", "gzip"); // Add POST data JSONObject json = new JSONObject(params); StringEntity jsonData = new StringEntity(json.toString(), "UTF-8"); jsonData.setContentType("application/json"); post.setEntity(jsonData); // Add timeouts for the connection { HttpParams httpParams = post.getParams(); // Set the timeout until a connection is established. int timeoutConnection = (int) (8 * Utils.SECOND); HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) which is the timeout for waiting for data. // use longer timeout when lazyServer-Feature is used int timeoutSocket = (int) ((Controller.getInstance().lazyServer()) ? 15 * Utils.MINUTE : 10 * Utils.SECOND); HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); post.setParams(httpParams); } logRequest(json); if (client == null) client = HttpClientFactory.getInstance().getHttpClient(post.getParams()); else client.setParams(post.getParams()); // Add SSL-Stuff if (credProvider != null) client.setCredentialsProvider(credProvider); } catch (URISyntaxException e) { hasLastError = true; lastError = "Invalid URI."; return null; } catch (Exception e) { hasLastError = true; lastError = "Error creating HTTP-Connection in (old) doRequest(): " + formatException(e); e.printStackTrace(); return null; } HttpResponse response; try { response = client.execute(post); // Execute the request } catch (ClientProtocolException e) { hasLastError = true; lastError = "ClientProtocolException in (old) doRequest(): " + formatException(e); return null; } catch (SSLPeerUnverifiedException e) { // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take // Not doing anything here since this error should happen only when no certificate is received from the // server. Log.w(TAG, "SSLPeerUnverifiedException in (old) doRequest(): " + formatException(e)); return null; } catch (SSLException e) { if ("No peer certificate".equals(e.getMessage())) { // Handle this by ignoring it, this occurrs very often when the connection is instable. Log.w(TAG, "SSLException in (old) doRequest(): " + formatException(e)); } else { hasLastError = true; lastError = "SSLException in (old) doRequest(): " + formatException(e); } return null; } catch (InterruptedIOException e) { Log.w(TAG, "InterruptedIOException in (old) doRequest(): " + formatException(e)); return null; } catch (SocketException e) { // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243#1565243 Log.w(TAG, "SocketException in (old) doRequest(): " + formatException(e)); return null; } catch (Exception e) { hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } // Try to check for HTTP Status codes int code = response.getStatusLine().getStatusCode(); if (code >= 400 && code < 600) { hasLastError = true; lastError = "Server returned status: " + code; return null; } InputStream instream = null; try { HttpEntity entity = response.getEntity(); if (entity != null) instream = entity.getContent(); // Try to decode gzipped instream, if it is not gzip we stay to normal reading Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) instream = new GZIPInputStream(instream); // Header size = response.getFirstHeader("Api-Content-Length"); // Log.d(TAG, "SIZE: " + size.getValue()); if (instream == null) { hasLastError = true; lastError = "Couldn't get InputStream in (old) Method doRequest(String url) [instream was null]"; return null; } } catch (Exception e) { if (instream != null) try { instream.close(); } catch (IOException e1) { // Empty! } hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } return instream; }
From source file:ninja.utils.NinjaTestBrowser.java
public String postXml(String url, Object object) { try {/*from w w w . j a va 2 s .co m*/ httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(new XmlMapper().writeValueAsString(object), "utf-8"); entity.setContentType("application/xml; charset=utf-8"); post.setEntity(entity); post.releaseConnection(); // Here we go! return EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8"); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:ninja.utils.NinjaTestBrowser.java
public String postJson(String url, Object object) { try {//from w w w . ja v a 2 s .c om httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = new HttpPost(url); StringEntity entity = new StringEntity(new ObjectMapper().writeValueAsString(object), "utf-8"); entity.setContentType("application/json; charset=utf-8"); post.setEntity(entity); post.releaseConnection(); // Here we go! return EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8"); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:io.mapzone.arena.csw.CswRequest.java
@Override public R execute(IProgressMonitor monitor) throws Exception { assert writer == null && buf == null; buf = new ByteArrayOutputStream(4096); writer = XMLOutputFactory.newInstance().createXMLStreamWriter(buf, DEFAULT_XML_ENCODING); writer = new IndentingXMLStreamWriter(writer); // write content out().writeStartDocument(DEFAULT_XML_ENCODING, "1.0"); writeRequest();//from w w w .j a v a2s. c o m prepare(monitor); out().writeEndElement(); out().writeEndDocument(); out().flush(); String content = buf.toString(DEFAULT_XML_ENCODING); log.info(content); // execute POST // XXX streaming content would be cool, but probably waste of effort HttpPost post = new HttpPost(baseUrl.get()); StringEntity entity = new StringEntity(content, DEFAULT_XML_ENCODING); entity.setContentType("application/xml"); post.setEntity(entity); // read response try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.get().execute(post); InputStream in = response.getEntity().getContent();) { // check return code StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { throw new IOException(status.getReasonPhrase() + " (" + status.getStatusCode() + ")"); } // handle response System.out.print("RESPONSE: "); TeeInputStream tee = new TeeInputStream(in, System.out); return handleResponse(tee, monitor); } finally { writer = null; buf = null; } }
From source file:Servlet.Change.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from ww w .ja va 2 s .c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //grabbing the event parameter String eventUrl = request.getParameter("eventUrl"); System.out.print(eventUrl); //Obtaining authority of event OAuthConsumer consumer = new DefaultOAuthConsumer("test6-40942", "oQ4q4oBiv9y4jPr7"); URL url = new URL(eventUrl); HttpURLConnection requestUrl = (HttpURLConnection) url.openConnection(); consumer.sign(requestUrl); requestUrl.connect(); //Reading in the xml file as a string String result = null; StringBuilder sb = new StringBuilder(); InputStream is = new BufferedInputStream(requestUrl.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String inputLine = ""; while ((inputLine = br.readLine()) != null) { sb.append(inputLine); } result = sb.toString(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource src = new InputSource(); src.setCharacterStream(new StringReader(result)); //parsing elements by name tags from event url Document doc = builder.parse(src); String creatorName = doc.getElementsByTagName("fullName").item(0).getTextContent(); String companyName = doc.getElementsByTagName("name").item(0).getTextContent(); String edition = doc.getElementsByTagName("editionCode").item(0).getTextContent(); String returnUrl = doc.getElementsByTagName("returnUrl").item(0).getTextContent(); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost xmlResponse = new HttpPost(returnUrl); StringEntity input = new StringEntity( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><result><success>true</success><message>Account change successful</message>"); input.setContentType("text/xml"); xmlResponse.setEntity(input); httpClient.execute(xmlResponse); } catch (OAuthMessageSignerException ex) { Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex); } catch (OAuthExpectationFailedException ex) { Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex); } catch (OAuthCommunicationException ex) { Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(Change.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.t2.drupalsdk.ServicesClient.java
public void put(String url, JSONObject params, AsyncHttpResponseHandler responseHandler) { StringEntity se = null; try {/* w ww.j ava 2 s .co m*/ se = new StringEntity(params.toString()); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); Log.d(TAG, "url = " + getAbsoluteUrl(url)); mAsyncHttpClient.put(null, getAbsoluteUrl(url), se, "application/json", responseHandler); }