List of usage examples for org.apache.http.entity StringEntity setContentType
public void setContentType(Header header)
From source file:com.ibm.watson.developer_cloud.service.Request.java
/** * Adds string content to the request (used with POST/PUT). This will * encapsulate the string into a// w w w. j a v a2s . c om * {@link org.apache.http.entity.StringEntity StringEntity} * encoded with UTF-8 * * @param content * the content to POST/PUT * @param contentType * the HTTP contentType to use. * * @return this * @throws UnsupportedEncodingException */ public Request withContent(String content, String contentType) throws UnsupportedEncodingException { StringEntity stringEntity = new StringEntity(content, UTF_8); if (contentType != null) { stringEntity.setContentType(contentType); } return withEntity(stringEntity); }
From source file:DataSci.main.JsonRequestResponseController.java
/** * Call REST API for retrieving prediction from Azure ML * @return response from the REST API/* w ww. ja va2 s. c om*/ */ public String rrsHttpPost() { HttpPost post; HttpClient client; StringEntity entity; try { // create HttpPost and HttpClient object post = new HttpPost(apiurl); client = HttpClientBuilder.create().build(); // setup output message by copying JSON body into // apache StringEntity object along with content type entity = new StringEntity(jsonBody/*, HTTP.UTF_8*/); // entity.setContentEncoding(HTTP.UTF_8); entity.setContentType("text/json"); // add HTTP headers post.setHeader("Accept", "text/json"); post.setHeader("Accept-Charset", "UTF-8"); // set Authorization header based on the API key post.setHeader("Authorization", ("Bearer " + apikey)); post.setEntity(entity); // Call REST API and retrieve response content HttpResponse authResponse = client.execute(post); return EntityUtils.toString(authResponse.getEntity()); } catch (Exception e) { return e.toString(); } }
From source file:com.flattr4android.rest.FlattrRestClient.java
protected HttpResponse sendRequest(String uri, String method, String content) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException, FlattrServerResponseException { HttpRequestBase req;/*from ww w . j a v a 2 s . c o m*/ if (method.equals("GET")) { req = new HttpGet("http://api.flattr.com" + uri); } else { req = new HttpPost("http://api.flattr.com" + uri); if (content != null) { StringEntity body = new StringEntity("data=" + URLEncoder.encode(content, "utf-8")); body.setContentType("application/x-www-form-urlencoded"); ((HttpPost) req).setEntity(body); } } consumer.sign(req); HttpResponse resp = getHttpClient().execute(req); int reqCode; reqCode = resp.getStatusLine().getStatusCode(); if (reqCode != 200) { if (reqCode == 401) { throw new AuthenticationException(resp); } else { throw new FlattrServerResponseException(resp); } } return resp; }
From source file:com.siddroid.offlinews.SendOffline.java
/** * Send json post./* w ww .j av a 2 s . co m*/ * This function sends a JSON request to webservice * @param url the url of webservice * @param req the req for the webservice * @return the result as object */ public Object sendJsonPost(String url, String req) { DefaultHttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(url); /*create entity of request to be sent with service*/ StringEntity se = new StringEntity(req); /*Add headers*/ se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); Log.d("CHECK", "JSON: " + req); /*set Entity*/ post.setEntity(se); HttpResponse response = client.execute(post); if (response != null) {//check response Log.d("CHECK", "Response: " + response); InputStream in = response.getEntity().getContent(); Log.d("CHECK", "in stream: " + in); /*returns result object after processing inputstream*/ return sendResponse(in); } else { Log.e("CHECK", "Response found null"); return null; } } catch (Exception e) { Log.e("CHECK", e.toString()); } return null; }
From source file:com.cloudant.client.org.lightcouch.CouchDbClientBase.java
/** * Sets a JSON String as a request entity. * * @param httpRequest The request to set entity. * @param json The JSON String to set. *///from ww w . j a v a 2 s.c o m private void setEntity(HttpEntityEnclosingRequestBase httpRequest, String json) { StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); httpRequest.setEntity(entity); }
From source file:net.java.sip.communicator.impl.protocol.sip.xcap.BaseHttpXCapClient.java
/** * Puts the resource to the server.//from ww w . java 2 s .com * * @param resource the resource to be saved on the server. * @return the server response. * @throws IllegalStateException if the user has not been connected. * @throws XCapException if there is some error during operation. */ public XCapHttpResponse put(XCapResource resource) throws XCapException { DefaultHttpClient httpClient = null; try { httpClient = createHttpClient(); URI resourceUri = getResourceURI(resource.getId()); HttpPut putMethod = new HttpPut(resourceUri); putMethod.setHeader("Connection", "close"); StringEntity stringEntity = new StringEntity(resource.getContent()); stringEntity.setContentType(resource.getContentType()); stringEntity.setContentEncoding("UTF-8"); putMethod.setEntity(stringEntity); if (logger.isDebugEnabled()) { String logMessage = String.format("Puting resource %1s to the server %2s", resource.getId().toString(), resource.getContent()); logger.debug(logMessage); } HttpResponse response = httpClient.execute(putMethod); return createResponse(response); } catch (IOException e) { String errorMessage = String.format("%1s resource cannot be put", resource.getId().toString()); throw new XCapException(errorMessage, e); } finally { if (httpClient != null) httpClient.getConnectionManager().shutdown(); } }
From source file:com.nebkat.plugin.cm.CMPlugin.java
@EventHandler @CommandFilter("download") public void onDownloadCommand(CommandEvent e) { if (e.getParams().length < 1) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": " + DOWNLOAD_URL); } else {/* w w w. j a va2s. c o m*/ Config.Device device = null; for (List<Config.Device> devices : mConfig.devices.values()) { for (Config.Device d : devices) { if (d.code.equalsIgnoreCase(e.getParams()[0])) { device = d; break; } } } if (device == null) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Unknown device " + e.getParams()[0]); return; } HttpPost post = new HttpPost(DOWNLOAD_API_URL); GetCMApiRequest request = new GetCMApiRequest(e.getParams()[0]); StringEntity json; try { json = new StringEntity(new Gson().toJson(request)); } catch (UnsupportedEncodingException uee) { Log.wtf(TAG, uee); return; } json.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(json); // Execute the request HttpContext context = new BasicHttpContext(); HttpResponse response; try { response = ConnectionManager.getHttpClient().execute(post, context); } catch (IOException ex) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching data"); return; } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching data"); post.abort(); return; } try (BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent()))) { GetCMApiResults results = mGson.fromJson(reader, GetCMApiResults.class); if (results.result.size() > 0) { GetCMApiResults.Result latest = results.result.get(0); Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Latest build (" + latest.channel + ") for " + device.name + ": " + latest.url + " [" + latest.md5sum.substring(0, 6) + "]"); } else { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": No builds for " + device.name); } } catch (IOException ioe) { Irc.message(e.getSession(), e.getTarget(), e.getSource().getNick() + ": Error fetching data"); } } }
From source file:org.xwiki.android.rest.HttpConnector.java
/** * Perform HTTP Post method execution and return its response status * /*from w w w .j a va 2s.co m*/ * @param Uri URL of XWiki RESTful API * @param content content to be posted to the server * @return status code of the Post method execution */ public String postRequest(String Uri, String content) { initialize(); HttpPost request = new HttpPost(); try { requestUri = new URI(Uri); } catch (URISyntaxException e) { e.printStackTrace(); } setCredentials(); request.setURI(requestUri); Log.d("Request URL", Uri); try { Log.d("Post content", "content=" + content); StringEntity se = new StringEntity(content, "UTF-8"); se.setContentType("application/xml"); // se.setContentType("text/plain"); request.setEntity(se); request.setHeader("Content-Type", "application/xml;charset=UTF-8"); response = client.execute(request); Log.d("Response status", response.getStatusLine().toString()); return response.getStatusLine().toString(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "error"; }
From source file:org.xwiki.android.rest.HttpConnector.java
/** * Perform HTTP Put method execution and return its response status * //from ww w .j a va 2 s . co m * @param Uri URL of XWiki RESTful API * @param content content to be posted to the server * @return status code of the Put method execution */ public String putRequest(String Uri, String content) { initialize(); HttpPut request = new HttpPut(); try { requestUri = new URI(Uri); } catch (URISyntaxException e) { e.printStackTrace(); } setCredentials(); request.setURI(requestUri); Log.d("Request URL", Uri); try { Log.d("Put content", "content=" + content); StringEntity se = new StringEntity(content, "UTF-8"); se.setContentType("application/xml"); // se.setContentType("text/plain"); request.setEntity(se); request.setHeader("Content-Type", "application/xml;charset=UTF-8"); response = client.execute(request); Log.d("Response status", response.getStatusLine().toString()); return response.getStatusLine().toString(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "error"; }
From source file:net.rcarz.jiraclient.RestClient.java
private JSON request(HttpEntityEnclosingRequestBase req, String payload) throws RestException, IOException { if (payload != null) { StringEntity ent = null; try {//from w w w . jav a 2 s . com ent = new StringEntity(payload, "UTF-8"); ent.setContentType("application/json"); } catch (UnsupportedEncodingException ex) { /* utf-8 should always be supported... */ } req.addHeader("Content-Type", "application/json"); req.setEntity(ent); } return request(req); }