List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str) throws UnsupportedEncodingException
From source file:playn.android.AndroidHeadlessNet.java
private void doHttp(final boolean isPost, final String url, final String data, final Callback<String> callback) { platform.invokeAsync(new Runnable() { @Override/* ww w . j a va 2s . c om*/ public void run() { HttpClient httpclient = new DefaultHttpClient(); HttpRequestBase req = null; if (isPost) { HttpPost httppost = new HttpPost(url); if (data != null) { try { httppost.setEntity(new StringEntity(data)); } catch (UnsupportedEncodingException e) { platform.notifyFailure(callback, e); } } req = httppost; } else { req = new HttpGet(url); } try { HttpResponse response = httpclient.execute(req); StatusLine status = response.getStatusLine(); int code = status.getStatusCode(); if (code == HttpStatus.SC_OK) { platform.notifySuccess(callback, EntityUtils.toString(response.getEntity())); } else { platform.notifyFailure(callback, new HttpException(code, status.getReasonPhrase())); } } catch (Exception e) { platform.notifyFailure(callback, e); } } @Override public String toString() { return "AndroidNet.doHttp(" + isPost + ", " + url + ")"; } }); }
From source file:org.apache.stratos.kubernetes.client.rest.RestClient.java
/** * Handle http post request. Return String *//w w w . j a v a 2 s. c o 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:at.ac.tuwien.dsg.elasticdaasclient.testing.RestfulWSClient.java
public String callPutMethod(String xmlString) { String rs = ""; try {// w w w .j a v a 2 s.c om //HttpGet method = new HttpGet(url); StringEntity inputKeyspace = new StringEntity(xmlString); Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Connection .. " + url); HttpPut request = new HttpPut(url); request.addHeader("content-type", "application/xml; charset=utf-8"); request.addHeader("Accept", "application/xml, multipart/related"); request.setEntity(inputKeyspace); HttpResponse methodResponse = this.getHttpClient().execute(request); int statusCode = methodResponse.getStatusLine().getStatusCode(); Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Status Code: " + statusCode); BufferedReader rd = new BufferedReader(new InputStreamReader(methodResponse.getEntity().getContent())); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } rs = result.toString(); // System.out.println("Response String: " + result.toString()); } catch (Exception ex) { } return rs; }
From source file:db.dao.Dao.java
public HttpResponse add(String url, Object entity) { url = checkIfLocal(url);/* www . j ava 2 s . c om*/ String usernamepassword = "Pepijn:Mores"; String encoded = Base64.encodeBase64String(usernamepassword.getBytes()); HttpClient client = HttpClientBuilder.create().build(); HttpPost postRequest = new HttpPost(url); postRequest.setHeader("content-type", "application/json"); postRequest.setHeader("Authorization", encoded); String entityToJson = null; try { ObjectMapper mapper = new ObjectMapper(); entityToJson = mapper.writeValueAsString(entity); } catch (JsonProcessingException ex) { Logger.getLogger(ArticleDao.class.getName()).log(Level.SEVERE, null, ex); } StringEntity jsonString = null; try { jsonString = new StringEntity(entityToJson); } catch (UnsupportedEncodingException ex) { Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex); } postRequest.setEntity(jsonString); HttpResponse response = null; try { response = client.execute(postRequest); } catch (IOException ex) { Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex); } return response; }
From source file:sh.calaba.driver.server.DriverRegistrationHandler.java
/** * Performs actually the registration of the calabash driver node into the grid hub. * // w w w .j a v a2 s . c o m * @throws Exception On registration errors. */ public void performRegsitration() throws Exception { String tmp = "http://" + config.getHubHost() + ":" + config.getHubPort() + "/grid/register"; HttpClient client = HttpClientFactory.getClient(); URL registration = new URL(tmp); if (logger.isDebugEnabled()) { logger.debug("Registering the node to hub :" + registration); } BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", registration.toExternalForm()); JSONObject nodeConfig = getNodeConfig(); r.setEntity(new StringEntity(nodeConfig.toString())); HttpHost host = new HttpHost(registration.getHost(), registration.getPort()); HttpResponse response = client.execute(host, r); if (response.getStatusLine().getStatusCode() != 200) { throw new CalabashException("Error sending the registration request."); } }
From source file:demo.web.goodKarma.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w ww.j a v a 2 s . com*/ * * @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 { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet goodKarma</title>"); out.println("</head>"); out.println("<body>"); out.println("</body>"); out.println("</html>"); String addresse = "http://localhost:8090/api"; JSONObject jsonLogin = new JSONObject(); jsonLogin.put("name", "MyTest"); jsonLogin.put("password", "password"); HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead HttpPost requestHttpPostLogin; requestHttpPostLogin = new HttpPost(addresse + "/login"); StringEntity paramsLogin = new StringEntity(jsonLogin.toString()); requestHttpPostLogin.addHeader("content-type", "application/json"); requestHttpPostLogin.setEntity(paramsLogin); HttpResponse responseHttpResponse = httpClient.execute(requestHttpPostLogin); HttpEntity entity = responseHttpResponse.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); out.print(responseString); JSONObject obj = new JSONObject(responseString); out.println("mytoken" + obj.getString("token")); //John JSONObject jsonPS = new JSONObject(); jsonPS.put("name", "karma"); HttpClient httpClientPS = HttpClientBuilder.create().build(); //Use this instead HttpPost requestHttpPostPS; requestHttpPostPS = new HttpPost(addresse + "/pointScales"); StringEntity paramsPS = new StringEntity(jsonPS.toString()); requestHttpPostPS.addHeader("content-type", "application/json"); requestHttpPostPS.addHeader("token", obj.getString("token")); requestHttpPostPS.setEntity(paramsPS); HttpResponse responseHttpResponsePS = httpClientPS.execute(requestHttpPostPS); } }
From source file:co.cask.cdap.client.rest.handlers.StreamInfoHttpRequestHandler.java
@Override public void handle(HttpRequest httpRequest, HttpResponse response, HttpContext httpContext) throws HttpException, IOException { RequestLine requestLine = httpRequest.getRequestLine(); String method = requestLine.getMethod(); int statusCode; if (!HttpMethod.GET.equals(method)) { statusCode = HttpStatus.SC_NOT_IMPLEMENTED; } else {/*from www.ja v a 2 s .c om*/ String uri = requestLine.getUri(); String streamName = TestUtils.getStreamNameFromUri(uri); if (TestUtils.AUTH_STREAM_NAME.equals(streamName)) { statusCode = TestUtils.authorize(httpRequest); } else if (streamName.contains(TestUtils.WRITER_TEST_STREAM_NAME_POSTFIX)) { statusCode = HttpStatus.SC_OK; } else { statusCode = TestUtils.getStatusCodeByStreamName(streamName); } if (statusCode == HttpStatus.SC_OK) { StringEntity entity = new StringEntity( "{\"partitionDuration\":3600000,\"indexInterval\":10000,\"ttl\":" + RestTest.STREAM_TTL + "}"); entity.setContentType(MediaType.APPLICATION_JSON); response.setEntity(entity); } } response.setStatusCode(statusCode); }
From source file:core.RESTCalls.RESTPost.java
public static String httpPost(String urlStr, String data, String type) { String result = null;/*from w w w. j av a2 s . c om*/ if (type == null || (type != null && !type.equals("text/plain") && !type.equals("xml") && !type.equals("json"))) { System.err.println( "\n[ERROR] RESTPost: Unknown input type (" + type + ") in the Http RESTful post request."); return null; } else { try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urlStr); StringEntity input = new StringEntity(data); if (type.equals("text/plain")) input.setContentType("text/plain"); else input.setContentType("application/" + type); post.setEntity(input); HttpResponse response = client.execute(post); if (response != null && response.getEntity() != null) { BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder total = new StringBuilder(); String line = null; while ((line = r.readLine()) != null) total.append(line + "\n"); result = total.toString(); } } catch (Exception ex) { ex.printStackTrace(); } return result; } }
From source file:at.ac.tuwien.dsg.depic.dataassetfunctionmanagement.util.TavernaRestAPI.java
public String callPutMethod(String xmlString) { String rs = ""; try {/* w ww. j a va 2s. c o m*/ //HttpGet method = new HttpGet(url); StringEntity inputKeyspace = new StringEntity(xmlString); Logger.getLogger(TavernaRestAPI.class.getName()).log(Level.INFO, "Connection .. " + url); HttpPut request = new HttpPut(url); request.addHeader("content-type", "application/xml; charset=utf-8"); // request.addHeader("Accept", "application/xml, multipart/related"); request.setEntity(inputKeyspace); HttpResponse methodResponse = this.getHttpClient().execute(request); int statusCode = methodResponse.getStatusLine().getStatusCode(); Logger.getLogger(TavernaRestAPI.class.getName()).log(Level.INFO, "Status Code: " + statusCode); BufferedReader rd = new BufferedReader(new InputStreamReader(methodResponse.getEntity().getContent())); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } rs = result.toString(); // System.out.println("Response String: " + result.toString()); } catch (Exception ex) { } return rs; }
From source file:com.subgraph.vega.ui.httpeditor.parser.HttpResponseParser.java
/** * Parse a HTTP response in a string.//from w ww. j a va 2 s. c om * * @param content HTTP response string. * @return HttpResponse, or null if the given HTTP response was empty. * @throws UnsupportedEncodingException */ public void parseResponse(final String content) throws UnsupportedEncodingException { final CharArrayBuffer buf = new CharArrayBuffer(0); buf.append(content); final ParserCursor bufCursor = new ParserCursor(0, buf.length()); final LineParser parser = new BasicLineParser(); if (parseStatusLine(parser, builder, buf, bufCursor) < 0) { return; } builder.clearHeaders(); parseHeaders(parser, builder, buf, bufCursor); if (!bufCursor.atEnd() && parseInlineEntities) { StringEntity entity = new StringEntity(buf.substring(bufCursor.getPos(), bufCursor.getUpperBound())); builder.setEntity(entity); } }