List of usage examples for org.apache.http.client.methods HttpPost setEntity
public void setEntity(final HttpEntity entity)
From source file:co.aurasphere.botmill.util.NetworkUtils.java
/** * Post json message./* www .j a v a 2 s . co m*/ * * @param jsonData the json data * @return the string */ public static String postTrainingString(String jsonData) { StringEntity stringEntity; try { stringEntity = new StringEntity(jsonData); stringEntity.setContentType("application/json"); HttpPost post = new HttpPost( RasaBotMillContext.getRasaConfig().toString() + NetworkConstants.TRAIN_EP + concatToken()); post.setEntity(stringEntity); return send(post); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:com.geekandroid.sdk.pay.utils.Util.java
public static byte[] httpPost(String url, String entity) { if (url == null || url.length() == 0) { Log.e(TAG, "httpPost, url is null"); return null; }//from w w w . ja va 2 s. c om HttpClient httpClient = getNewHttpClient(); HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(new StringEntity(entity)); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse resp = httpClient.execute(httpPost); if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode()); return null; } return EntityUtils.toByteArray(resp.getEntity()); } catch (Exception e) { Log.e(TAG, "httpPost exception, e = " + e.getMessage()); e.printStackTrace(); return null; } }
From source file:org.jenkinsci.plugins.fabric8.support.HubotClient.java
public static String notify(TaskListener listener, String room, String message) throws java.io.IOException { log(listener, "Hubot sending to room " + room + " => " + message); if (Strings.isNullOrBlank(room)) { log(listener, "you must specify a room!"); return null; }/*w w w .j a v a 2 s.c om*/ if (Strings.isNullOrBlank(message)) { log(listener, "you must specify a message!"); return null; } HttpHost host = RestClient.getHttpHost(listener, "hubot"); if (host != null) { String roomWithSlugPrefix = room; if (roomWithSlugPrefix.startsWith("#")) { roomWithSlugPrefix = roomWithSlugPrefix.substring(1); } if (!roomWithSlugPrefix.startsWith(ROOM_SLUG_PREFIX)) { roomWithSlugPrefix = ROOM_SLUG_PREFIX + roomWithSlugPrefix; } HttpPost post = new HttpPost("/hubot/notify/" + roomWithSlugPrefix); log(listener, "Posting to " + host.toString() + " url: " + post.getURI()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("message", message)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse response = RestClient.executeRequest(host, post); String result = RestClient.parse(response); log(listener, "Result: " + result); return result; } else { log(listener, "No service found!"); return null; } }
From source file:org.opencastproject.remotetest.server.resource.IngestResources.java
/** * //from ww w . jav a 2 s . com * @param type * Type of media to add: Track, Catalog, Attachment * */ public static HttpResponse add(TrustedHttpClient client, String type, String url, String flavor, String mediaPackage) throws Exception { HttpPost post = new HttpPost(getServiceUrl() + "add" + type); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("url", url)); params.add(new BasicNameValuePair("flavor", flavor)); params.add(new BasicNameValuePair("mediaPackage", mediaPackage)); post.setEntity(new UrlEncodedFormEntity(params)); return client.execute(post); }
From source file:gov.in.bloomington.georeporter.models.Open311.java
/** * POST new service request data to the endpoint * /*from ww w.ja v a2 s.c o m*/ * @param data * @return * JSONObject */ public static JSONArray postServiceRequest(List<NameValuePair> data) { HttpPost post = new HttpPost(mBaseUrl + "/requests.json"); JSONArray response = new JSONArray(); try { post.setEntity(new UrlEncodedFormEntity(data)); HttpResponse r = mClient.execute(post); response = new JSONArray(EntityUtils.toString(r.getEntity())); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return response; }
From source file:com.thed.zephyr.jenkins.utils.rest.Cycle.java
public static Long createCycle(ZephyrConfigModel zephyrData) { Long cycleId = 0L;//from ww w. j ava2 s. c o m HttpResponse response = null; try { String createCycleURL = URL_CREATE_CYCLES.replace("{SERVER}", zephyrData.getRestClient().getUrl()); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("E dd, yyyy hh:mm a"); String dateFormatForCycleCreation = sdf.format(date); JSONObject jObject = new JSONObject(); String cycleName = zephyrData.getCyclePrefix() + dateFormatForCycleCreation; SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MMM/yy"); String startDate = sdf1.format(date); GregorianCalendar gCal = new GregorianCalendar(); if (zephyrData.getCycleDuration().trim().equalsIgnoreCase("30 days")) { gCal.add(Calendar.DAY_OF_MONTH, +29); } else if (zephyrData.getCycleDuration().trim().equalsIgnoreCase("7 days")) { gCal.add(Calendar.DAY_OF_MONTH, +6); } String endDate = sdf1.format(gCal.getTime()); jObject.put("name", cycleName); jObject.put("projectId", zephyrData.getZephyrProjectId()); jObject.put("versionId", zephyrData.getVersionId()); jObject.put("startDate", startDate); jObject.put("endDate", endDate); StringEntity se = new StringEntity(jObject.toString(), "utf-8"); HttpPost createCycleRequest = new HttpPost(createCycleURL); createCycleRequest.setHeader("Content-Type", "application/json"); createCycleRequest.setEntity(se); response = zephyrData.getRestClient().getHttpclient().execute(createCycleRequest, zephyrData.getRestClient().getContext()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { JSONObject cycleObj = new JSONObject(string); cycleId = cycleObj.getLong("id"); } catch (JSONException e) { e.printStackTrace(); } } else if (statusCode == 405) { try { throw new ClientProtocolException("ZAPI plugin license is invalid" + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } else { try { throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } return cycleId; }
From source file:com.webber.webber.client.NetworkUtilities.java
/** * Connects to the webber server, authenticates the provided * username and password./* w w w . j a v a 2 s . c o m*/ * * @param username The server account username * @param password The server account password * @return String The authentication token returned by the server (or null) */ public static WebberAccount authenticate(String username, String password) { final HttpResponse resp; final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, username)); params.add(new BasicNameValuePair(PARAM_PASSWORD, password)); final HttpEntity entity; try { entity = new UrlEncodedFormEntity(params); } catch (final UnsupportedEncodingException e) { // this should never happen. throw new IllegalStateException(e); } Log.i(TAG, "Authenticating to: " + AUTH_URI); final HttpPost post = new HttpPost(AUTH_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); try { resp = getHttpClient().execute(post); String strResult = EntityUtils.toString(resp.getEntity()); Log.v(TAG, strResult); JSONObject userObject = new JSONObject(strResult); boolean valid = userObject.getBoolean("valid"); String uid = null; String realname = null; String authToken = null; if (valid) { WebberAccount wa = new WebberAccount(); wa.uid = userObject.getString("uid"); wa.realname = userObject.getString("realname"); wa.authToken = userObject.getString("authToken"); if ((wa.authToken != null) && (wa.authToken.length() > 0)) { Log.v(TAG, "Successful authentication"); return wa; } } else { Log.e(TAG, "Error authenticating" + resp.getStatusLine()); return null; } } catch (final ClientProtocolException e) { // TODO Auto-generated catch block Log.v(TAG, e.toString()); } catch (final IOException e) { Log.e(TAG, "IOException when getting authtoken", e); return null; } catch (final JSONException e) { Log.v(TAG, e.toString()); } finally { Log.v(TAG, "getAuthtoken completing"); } return null; }
From source file:edu.cmu.android.restaurant.authentication.NetworkUtilities.java
/** * Fetches status messages for the user's friends from the server * //from w ww .j a v a 2 s . c o m * @param account * The account being synced. * @param authtoken * The authtoken stored in the AccountManager for the account * @return list The list of status messages received from the server. */ public static List<User.Status> fetchFriendStatuses(Account account, String authtoken) throws JSONException, ParseException, IOException, AuthenticationException { final ArrayList<User.Status> statusList = new ArrayList<User.Status>(); final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, account.name)); params.add(new BasicNameValuePair(PARAM_PASSWORD, authtoken)); HttpEntity entity = null; entity = new UrlEncodedFormEntity(params); final HttpPost post = new HttpPost(FETCH_STATUS_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); maybeCreateHttpClient(); final HttpResponse resp = mHttpClient.execute(post); final String response = EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. final JSONArray statuses = new JSONArray(response); for (int i = 0; i < statuses.length(); i++) { statusList.add(User.Status.valueOf(statuses.getJSONObject(i))); } } else { if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in fetching friend status list"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in fetching friend status list"); throw new IOException(); } } return statusList; }
From source file:edu.cmu.android.restaurant.authentication.NetworkUtilities.java
/** * Connects to the Voiper server, authenticates the provided username and * password./*www. java 2 s . c om*/ * * @param username * The user's username * @param password * The user's password * @param handler * The hander instance from the calling UI thread. * @param context * The context of the calling Activity. * @return boolean The boolean result indicating whether the user was * successfully authenticated. */ public static boolean authenticate(String username, String password, Handler handler, final Context context) { final HttpResponse resp; final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, username)); params.add(new BasicNameValuePair(PARAM_PASSWORD, password)); HttpEntity entity = null; try { entity = new UrlEncodedFormEntity(params); } catch (final UnsupportedEncodingException e) { // this should never happen. throw new AssertionError(e); } final HttpPost post = new HttpPost(AUTH_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); maybeCreateHttpClient(); try { resp = mHttpClient.execute(post); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Successful authentication"); } sendResult(true, handler, context); return true; } else { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "Error authenticating" + resp.getStatusLine()); } sendResult(false, handler, context); return false; } } catch (final IOException e) { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "IOException when getting authtoken", e); } sendResult(false, handler, context); return false; } finally { if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "getAuthtoken completing"); } } }
From source file:com.meltmedia.cadmium.cli.UndeployCommand.java
/** * Sends the undeploy command to a Cadmium-Deployer war. * // w ww . j ava2 s .c om * @param url The uri to a Cadmium-Deployer war. * @param warName The war to undeploy. * @param token The Github API token used for authentication. * @throws Exception */ public static void undeploy(String url, String warName, String token) throws Exception { HttpClient client = httpClient(); HttpPost del = new HttpPost(url + "/system/undeploy"); addAuthHeader(token, del); del.addHeader("Content-Type", MediaType.APPLICATION_JSON); UndeployRequest req = new UndeployRequest(); req.setWarName(warName); del.setEntity(new StringEntity(new Gson().toJson(req), "UTF-8")); HttpResponse resp = client.execute(del); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String respStr = EntityUtils.toString(resp.getEntity()); if (!respStr.equals("ok")) { throw new Exception("Failed to undeploy " + warName); } else { System.out.println("Undeployment of " + warName + " successful"); } } else { System.err.println("Failed to undeploy " + warName); System.err .println(resp.getStatusLine().getStatusCode() + ": " + EntityUtils.toString(resp.getEntity())); } }