List of usage examples for org.apache.http.entity StringEntity StringEntity
public StringEntity(String str) throws UnsupportedEncodingException
From source file:com.mysoft.b2b.event.util.HttpUtil.java
/** * http???//from ww w. j a v a 2 s. co m * @param uri ? * @param body ? */ public static Integer send(String uri, String body) { if (StringUtils.isEmpty(uri) || StringUtils.isEmpty(body)) return null; HttpClient client = new DefaultHttpClient(); try { HttpPost post = new HttpPost(uri + "/dealEvent.do"); post.addHeader("Content-Type", "application/json;charset=UTF-8"); HttpEntity entity = new StringEntity(body); post.setEntity(entity); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); return code; } catch (Exception e) { logger.error("http???" + e); } return null; }
From source file:com.socioffice.grabmenu.model.JSONRequest.java
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) { try {/*from w w w . ja v a 2 s. co m*/ DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); StringEntity se; se = new StringEntity(jsonObjSend.toString()); // Set HTTP parameters httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader("Content-type", "application/json"); // only set this parameter if you would like to use gzip compression httpPostRequest.setHeader("Accept-Encoding", "gzip"); long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]"); // Get hold of the response entity (-> the data): HttpEntity entity = response.getEntity(); if (entity != null) { // Read the content stream InputStream instream = entity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } // convert content stream to a String String resultString = convertStreamToString(instream); instream.close(); resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and // "]" // Transform the String into a JSONObject JSONObject jsonObjRecv = new JSONObject(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<jsonobject>\n" + jsonObjRecv.toString() + "\n</jsonobject>"); return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }
From source file:manager.computerVisionManager.java
private static void getJson(String path) { System.out.println("Get Description from https://westus.api.cognitive.microsoft.com/vision/v1.0/describe"); try {// w w w . j a v a 2s .c om URIBuilder builder = new URIBuilder("https://westus.api.cognitive.microsoft.com/vision/v1.0/describe"); builder.setParameter("maxCandidates", "1"); URI uri = builder.build(); HttpPost request = new HttpPost(uri); request.setHeader("Content-Type", "application/json"); request.setHeader("Ocp-Apim-Subscription-Key", "d7f6ef12e41c4f8c8e72d12a890fa703"); // Request body StringEntity reqEntity = new StringEntity("{\"url\":\"" + path + "\"}"); System.out.println("Request String: " + reqEntity.toString()); request.setEntity(reqEntity); HttpResponse response = httpclient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { String respuesta = EntityUtils.toString(entity); JSONParser lector = new JSONParser(); StringReader SR = new StringReader(respuesta); try { JSONObject temp = (JSONObject) lector.parse(SR); json = (JSONObject) temp.get("description"); } catch (org.json.simple.parser.ParseException e) { System.err.println(e.getMessage()); } } } catch (IOException | URISyntaxException | ParseException e) { System.err.println(e.getMessage()); } }
From source file:ca.dal.cs.csci4126.quizboard.library.HttpClient.java
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) { try {/*from ww w.j av a 2s . co m*/ DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); StringEntity se; se = new StringEntity(jsonObjSend.toString()); // Set HTTP parameters httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader("Content-type", "application/json"); httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]"); // Get hold of the response entity (-> the data): HttpEntity entity = response.getEntity(); if (entity != null) { // Read the content stream InputStream instream = entity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } // convert content stream to a String String resultString = convertStreamToString(instream); instream.close(); resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]" // Transform the String into a JSONObject JSONObject jsonObjRecv = new JSONObject(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }
From source file:com.example.montxu.magik_repair.HttpClient.java
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) { try {/* w w w.j av a2s .c o m*/ DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); StringEntity se; se = new StringEntity(jsonObjSend.toString()); // Set HTTP parameters httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader("Content-type", "application/json"); httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]"); // Get hold of the response entity (-> the data): HttpEntity entity = response.getEntity(); if (entity != null) { // Read the content stream InputStream instream = entity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } // convert content stream to a String String resultString = convertStreamToString(instream); instream.close(); //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]" // Transform the String into a JSONObject JSONObject jsonObjRecv = new JSONObject(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }
From source file:app.wz.HttpClient.java
public static String SendHttpPost(String URL, JSONObject jsonObjSend) { try {/*from www. j a va 2s . c om*/ DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); StringEntity se; se = new StringEntity(jsonObjSend.toString()); // Set HTTP parameters httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader("Content-type", "application/json"); httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]"); // Get hold of the response entity (-> the data): HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); // // Read the content stream // InputStream instream = entity.getContent(); // Header contentEncoding = response.getFirstHeader("Content-Encoding"); // if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { // instream = new GZIPInputStream(instream); // } // // // convert content stream to a String // String resultString= convertStreamToString(instream); // instream.close(); // resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]" // // // Transform the String into a JSONObject // JSONObject jsonObjRecv = new JSONObject(resultString); // // Raw DEBUG output of our received JSON object: // Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>"); // // return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }
From source file:org.roda.core.util.RESTClientUtility.java
public static <T extends Serializable> T sendPostRequest(T element, Class<T> elementClass, String url, String resource, String username, String password) throws RODAException { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); String basicAuthToken = new String(Base64.encode((username + ":" + password).getBytes())); HttpPost httpPost = new HttpPost(url + resource); httpPost.setHeader("Authorization", "Basic " + basicAuthToken); httpPost.addHeader("content-type", "application/json"); httpPost.addHeader("Accept", "application/json"); try {/*from w w w . j a v a 2 s. c o m*/ httpPost.setEntity(new StringEntity(JsonUtils.getJsonFromObject(element))); HttpResponse response; response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); int responseStatusCode = response.getStatusLine().getStatusCode(); if (responseStatusCode == 201) { return JsonUtils.getObjectFromJson(responseEntity.getContent(), elementClass); } else { throw new RODAException("POST request response status code: " + responseStatusCode); } } catch (IOException e) { throw new RODAException("Error sending POST request", e); } }
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 ww w . j a v a2s . 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:DdaApiUtils.java
public static void queryHoldingsAddReplaceEndpoint(String channelId, String databaseCode, String providerCode, String baseUrl) throws Exception { String url = (baseUrl + providerCode + "/libraries/" + channelId + "/" + databaseCode + "/holdings/addReplace?seqnum=1"); System.out.println();/*from w w w . j ava 2 s. co m*/ System.out.println("Request URL is: " + url); StringEntity jsonPacket = new StringEntity("[{ \"id\": \"10778603\", \"owned\": true }]"); CloseableHttpResponse response = HttpUtils.processHttpPostRequest(url, jsonPacket); int serverResponse = HttpUtils.getResponseStatusCode(response); String reasonPhrase = HttpUtils.getReasonPhrase(response); System.out.println(); if (serverResponse == 200) { System.out.println("Update holdings request for provider " + providerCode + " was successful."); } else { System.out.println("Update holdings for provider " + providerCode + " was NOT successful."); System.out.println("Server response was: " + serverResponse); System.out.println("Server reason phrase was: " + reasonPhrase); } }
From source file:com.ibm.xsp.xflow.activiti.util.HttpClientUtil.java
public static String post(String url, Cookie[] cookies, String content) { String body = null;/*www .j a v a2s .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; }