List of usage examples for org.apache.http.client.methods HttpPost setEntity
public void setEntity(final HttpEntity entity)
From source file:pj.rozkladWKD.HttpClient.java
public static JSONObject SendHttpPost(List<NameValuePair> nameValuePairs) throws JSONException, ClientProtocolException, IOException { // Create a new HttpClient and Post Header DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.mmaj.nazwa.pl/rozkladwkd/listener2.php"); nameValuePairs.add(new BasicNameValuePair("app_ver", RozkladWKD.APP_VERSION)); // Add your data httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF_8")); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); 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); }//from w ww. j a v a 2 s . c om // 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 if (RozkladWKD.DEBUG_LOG) { Log.i(TAG, "result: " + resultString); } JSONObject jsonObjRecv = new JSONObject(resultString); // Raw DEBUG output of our received JSON object: if (RozkladWKD.DEBUG_LOG) { Log.i(TAG, "<jsonobject>\n" + jsonObjRecv.toString() + "\n</jsonobject>"); } return jsonObjRecv; } return null; }
From source file:com.photon.phresco.Screens.HttpRequest.java
/** * Send the JSON data to specified URL and get the httpResponse back * * @param sURL// w w w . j a v a 2 s . c o m * @param jObject * @return InputStream * @throws IOException */ public static InputStream post(String sURL, JSONObject jObject) throws IOException { HttpResponse httpResponse = null; InputStream is = null; HttpPost httpPostRequest = new HttpPost(sURL); HttpEntity entity; httpPostRequest.setHeader("Accept", "application/json"); httpPostRequest.setHeader(HTTP.CONTENT_TYPE, "application/json"); httpPostRequest.setEntity(new ByteArrayEntity(jObject.toString().getBytes("UTF-8"))); HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = TIME_OUT; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = TIME_OUT; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); httpResponse = httpClient.execute(httpPostRequest); if (httpResponse != null) { entity = httpResponse.getEntity(); is = entity.getContent(); } return is; }
From source file:org.wso2.security.tools.product.manager.handler.HttpRequestHandler.java
/** * Send HTTP POST request//from w w w . j a va 2s.com * * @param requestURI Requested URI * @return HTTPResponse after executing the command */ public static HttpResponse sendPostRequest(String requestURI, ArrayList<NameValuePair> parameters) { try { HttpClientBuilder clientBuilder = HttpClients.custom(); HttpClient httpClient = clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)) .build(); HttpPost httpPostRequest = new HttpPost(requestURI); for (NameValuePair parameter : parameters) { urlParameters.add(new BasicNameValuePair(parameter.getName(), parameter.getValue())); } httpPostRequest.setEntity(new UrlEncodedFormEntity(urlParameters)); return httpClient.execute(httpPostRequest); } catch (IOException e) { LOGGER.error("Error occurred while sending POST request to " + requestURI, e); } return null; }
From source file:topoos.APIAccess.APICaller.java
/** * Initiates an operation on topoos API. * /*from w w w . ja v a 2 s . c om*/ * @param operation * Represents the operation to be executed * @param result * Represents a result returned from a query to API topoos * @throws IOException * @throws TopoosException */ public static void ExecuteOperation(APIOperation operation, APICallResult result) throws IOException, TopoosException { HttpClient hc = new DefaultHttpClient(); if (!operation.ValidateParams()) throw new TopoosException(TopoosException.NOT_VALID_PARAMS); String OpURI = Constants.TOPOOSURIAPI + operation.ConcatParams(); if (Constants.DEBUGURL) { Log.d(Constants.TAG, OpURI); // appendLog(OpURI); } HttpPost post = new HttpPost(OpURI); // POST if (operation.getMethod().equals("POST")) { post.setEntity(operation.BodyParams()); } HttpResponse rp = hc.execute(post); HttpParams httpParams = hc.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, Constants.HTTP_WAITING_MILISECONDS); HttpConnectionParams.setSoTimeout(httpParams, Constants.HTTP_WAITING_MILISECONDS); if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result.setResult(EntityUtils.toString(rp.getEntity())); if (Constants.DEBUGURL) { Log.d(Constants.TAG, result.getResult()); // appendLog(result.getResult()); } result.setError(null); result.setParameters(); } else { switch (rp.getStatusLine().getStatusCode()) { case 400: throw new TopoosException(TopoosException.ERROR400); case 405: throw new TopoosException(TopoosException.ERROR405); default: throw new TopoosException("Error: " + rp.getStatusLine().getStatusCode() + ""); } } }
From source file:com.google.developers.gdgfirenze.mockep.AndroidSimulator.java
private static void postData(String url, JSONObject jsonSamplePacket) throws ClientProtocolException, IOException { HttpParams myParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myParams, 10000); HttpConnectionParams.setSoTimeout(myParams, 10000); HttpClient httpclient = new DefaultHttpClient(myParams); HttpPost httppost = new HttpPost(url.toString()); httppost.setHeader("Content-type", "application/json"); StringEntity se = new StringEntity(jsonSamplePacket.toString()); se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httppost.setEntity(se); HttpResponse response = httpclient.execute(httppost); String temp = EntityUtils.toString(response.getEntity()); System.out.println("JSON post response: " + temp); }
From source file:com.storageroomapp.client.util.Http.java
/** * POST to the url with the provided body. * @param url a String url/*from www.java2s . co m*/ * @param body a String with text for the request body * @return true if successful (response code < 400), false otherwise */ static public boolean post(String url, String body) { boolean success = false; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); HttpEntity entity = new StringEntity(body); httppost.setEntity(entity); // Be sure to add these headers or the StRoom API will NOT work! Header contentType = new BasicHeader("Content-Type", "application/json"); httppost.setHeader(contentType); Header accept = new BasicHeader("Accept", "*/*"); httppost.setHeader(accept); HttpResponse response = httpclient.execute(httppost); int code = response.getStatusLine().getStatusCode(); String reason = response.getStatusLine().getReasonPhrase(); success = code < 400; if (log.isDebugEnabled()) { log.debug("Http.post url [" + url + "] body [" + body + "] response code [" + code + "] reason [" + reason + "]"); } } catch (Exception e) { log.error("Http.post failed, with url [" + url + "]", e); } return success; }
From source file:com.openkm.applet.Util.java
/** * Upload scanned document to OpenKM/*from w ww. j a va2s.c om*/ * */ public static String createDocument(String token, String path, String fileName, String fileType, String url, List<BufferedImage> images) throws MalformedURLException, IOException { log.info("createDocument(" + token + ", " + path + ", " + fileName + ", " + fileType + ", " + url + ", " + images + ")"); File tmpDir = createTempDir(); File tmpFile = new File(tmpDir, fileName + "." + fileType); ImageOutputStream ios = ImageIO.createImageOutputStream(tmpFile); String response = ""; try { if ("pdf".equals(fileType)) { ImageUtils.writePdf(images, ios); } else if ("tif".equals(fileType)) { ImageUtils.writeTiff(images, ios); } else { if (!ImageIO.write(images.get(0), fileType, ios)) { throw new IOException("Not appropiated writer found!"); } } ios.flush(); ios.close(); if (token != null) { // Send image HttpClient client = new DefaultHttpClient(); MultipartEntity form = new MultipartEntity(); form.addPart("file", new FileBody(tmpFile)); form.addPart("path", new StringBody(path, Charset.forName("UTF-8"))); form.addPart("action", new StringBody("0")); // FancyFileUpload.ACTION_INSERT HttpPost post = new HttpPost(url + "/frontend/FileUpload;jsessionid=" + token); post.setHeader("Cookie", "jsessionid=" + token); post.setEntity(form); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); } else { // Store in disk String home = System.getProperty("user.home"); File dst = new File(home, tmpFile.getName()); copyFile(tmpFile, dst); response = "Image copied to " + dst.getPath(); } } finally { FileUtils.deleteQuietly(tmpDir); } log.info("createDocument: " + response); return response; }
From source file:org.broadinstitute.gatk.utils.help.ForumAPIUtils.java
private static String httpPost(String data, String URL) { try {//ww w. j a v a 2 s.c om DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(URL); StringEntity input = new StringEntity(data); input.setContentType("application/json"); postRequest.setEntity(input); 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 = ""; String line; System.out.println("Output from Server .... \n"); while ((line = br.readLine()) != null) { output += (line + '\n'); System.out.println(line); } br.close(); httpClient.getConnectionManager().shutdown(); return output; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:att.jaxrs.client.Library.java
public static String deleteLibrary(long content_id) { List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("content_id", Long.toString(content_id))); String resultStr = ""; try {/*ww w . ja v a2 s .c o m*/ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(Constants.DELETE_LIBRARY_RESOURCE); post.setEntity(new UrlEncodedFormEntity(urlParameters)); HttpResponse result = httpClient.execute(post); System.out.println(Constants.RESPONSE_STATUS_CODE + result); resultStr = Util.getStringFromInputStream(result.getEntity().getContent()); System.out.println(Constants.RESPONSE_BODY + resultStr); } catch (Exception e) { System.out.println(e.getMessage()); } return resultStr; }
From source file:com.attentec.ServerContact.java
/** * Posts POST request to url with data that from values. * Values are put together to a json object before they are sent to server. * postname = { subvar_1_name => subvar_1_value, * subvar_2_name => subvar_2_value * ...}// w w w . j av a 2 s. c om * postname_2 = {...} * ... * @param values hashtable with structure: * @param url path on the server to call * @param ctx calling context * @return JSONObject with data from rails server. * @throws Login.LoginException when login is wrong */ public static JSONObject postJSON(final Hashtable<String, List<NameValuePair>> values, final String url, final Context ctx) throws Login.LoginException { //fetch the urlbase urlbase = PreferencesHelper.getServerUrlbase(ctx); //create a JSONObject of the hashtable List<NameValuePair> pairs = new ArrayList<NameValuePair>(); Enumeration<String> postnames = values.keys(); String postname; List<NameValuePair> postvalues; JSONObject postdata; while (postnames.hasMoreElements()) { postname = (String) postnames.nextElement(); postvalues = values.get(postname); postdata = new JSONObject(); for (int i = 0; i < postvalues.size(); i++) { try { postdata.put(postvalues.get(i).getName(), postvalues.get(i).getValue()); } catch (JSONException e) { Log.w(TAG, "JSON fail"); return null; } } pairs.add(new BasicNameValuePair(postname, postdata.toString())); } //prepare the http call HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT); HttpClient client = new DefaultHttpClient(httpParams); HttpPost post = new HttpPost(urlbase + url); //Log.d(TAG, "contacting url: " + post.getURI()); try { post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8")); } catch (UnsupportedEncodingException e) { return null; } //call the server String response = null; ResponseHandler<String> responseHandler = new BasicResponseHandler(); try { response = client.execute(post, responseHandler); } catch (IOException e) { Log.e(TAG, "Failed in HTTP request: " + e.toString()); return null; } //Log.d(TAG, "Have contacted url success: " + post.getURI()); //read response JSONObject jsonresponse; try { jsonresponse = new JSONObject(response); } catch (JSONException e) { Log.e(TAG, "Incorrect response from server" + e.toString()); return null; } String responsestatus; try { responsestatus = jsonresponse.getString("Responsestatus"); } catch (JSONException e1) { return null; } if (!responsestatus.equals("Wrong login")) { return jsonresponse; } else { Log.w(TAG, "Wrong login"); throw new Login.LoginException("Wrong login"); } }