List of usage examples for org.apache.http.client.methods HttpPost HttpPost
public HttpPost(final String uri)
From source file:at.ac.tuwien.swa13.swazam.NetworkConnection.java
public void makeRequest(String taskId, String username, ISong song) { System.out.println("Telling server about " + taskId + ": Found " + song.toString()); try {/* ww w . ja va 2 s .co m*/ HttpClient client = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://" + server + ":8080/swazam-server/result"); postRequest.addHeader("Content-Type", "application/x-www-form-urlencoded"); postRequest.addHeader("Cache-Control", "no-cache"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("id", taskId)); nvps.add(new BasicNameValuePair("user", username)); nvps.add(new BasicNameValuePair("result", buildMetadataBody(song))); UrlEncodedFormEntity songEntity = new UrlEncodedFormEntity(nvps); postRequest.setEntity(songEntity); HttpResponse response = client.execute(postRequest); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { Logger.getLogger(NetworkConnection.class.getName()).log(Level.INFO, line); } } catch (IOException ex) { Logger.getLogger(NetworkConnection.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.jboss.aerogear.windows.mpns.internal.AbstractMpnsService.java
protected HttpPost postMessage(String subscriptionUri, byte[] requestBody, Collection<? extends Entry<String, String>> headers) { HttpPost method = new HttpPost(subscriptionUri); method.setEntity(new ByteArrayEntity(requestBody)); for (Entry<String, String> header : headers) { method.addHeader(header.getKey(), header.getValue()); }/*from w w w.jav a 2 s . com*/ return method; }
From source file:com.android.projecte.townportal.WeatherInfo.java
public JSONObject getJSONFromUrl(String url) { try {/*w w w .ja v a 2s.com*/ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); content = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(content, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } content.close(); json = sb.toString(); } catch (Exception e) { e.printStackTrace(); } try { jObj = new JSONObject(json); } catch (JSONException e) { e.printStackTrace(); } return jObj; }
From source file:driimerfinance.helpers.FinanceHelper.java
/** * Checks if the license is valid using the License Key Server * * @param license key to check/*from w w w . ja v a2s .co m*/ * @return validity of the license (true or false) */ public static boolean checkLicense(String licenseKey) { HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://driimerfinance.michaelkohler.info/checkLicense"); List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("key", licenseKey)); // pass the key to the server try { httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); } catch (UnsupportedEncodingException e) { return false; } HttpResponse response = null; try { response = httpclient.execute(httppost); // get the response from the server } catch (IOException e) { return false; } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = null; try { instream = entity.getContent(); @SuppressWarnings("resource") java.util.Scanner s = new java.util.Scanner(instream).useDelimiter("\\A"); // parse the response String responseString = s.hasNext() ? s.next() : ""; instream.close(); return responseString.contains("\"valid\":true"); // if the license is valid, return true, else false } catch (IllegalStateException | IOException e) { return false; } } return false; }
From source file:com.magnet.plugin.api.requests.PostRequest.java
@Override protected HttpRequestBase getRequest(RequestModel requestModel) { HttpPost httpPost = new HttpPost(requestModel.getTestUrl()); try {/*from ww w. j av a 2s. c o m*/ httpPost.setEntity(new StringEntity(requestModel.getRequest(), "UTF-8")); } catch (Exception e) { } return httpPost; }
From source file:com.networknt.client.oauth.TokenHelper.java
public static TokenResponse getToken(TokenRequest tokenRequest) throws ClientException { String url = tokenRequest.getServerUrl() + tokenRequest.getUri(); TokenResponse tokenResponse = null;//from ww w . java2s. c o m HttpPost httpPost = new HttpPost(url); httpPost.addHeader(Constants.AUTHORIZATION, getBasicAuthHeader(tokenRequest.getClientId(), tokenRequest.getClientSecret())); try { CloseableHttpClient client = Client.getInstance().getSyncClient(); httpPost.setEntity(getEntity(tokenRequest)); HttpResponse response = client.execute(httpPost); tokenResponse = handleResponse(response); } catch (JsonProcessingException jpe) { logger.error("JsonProcessingException: ", jpe); throw new ClientException("JsonProcessingException: ", jpe); } catch (UnsupportedEncodingException uee) { logger.error("UnsupportedEncodingException", uee); throw new ClientException("UnsupportedEncodingException: ", uee); } catch (IOException ioe) { logger.error("IOException: ", ioe); throw new ClientException("IOException: ", ioe); } return tokenResponse; }
From source file:com.aurel.track.license.LicenseHelperBL.java
public static String sendPOSTReq(List<BasicNameValuePair> params, String licenseProviderAddress) { String responseStr = ""; try {//from w ww .j ava2 s. c om HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(licenseProviderAddress); // Request parameters and other properties. httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); //Execute and get the response. HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); responseStr = StringArrayParameterUtils.getStringFromInputStream(instream); try { // do something useful } finally { instream.close(); } } } catch (Exception ex) { LOGGER.error(ExceptionUtils.getStackTrace(ex)); } int idx = responseStr.indexOf("}<!DOCTYPE HTML", 0); if (idx > 0) { responseStr = responseStr.substring(0, idx + 1); } return responseStr; }
From source file:sk.mpage.androidsample.drawerwithauthenticator.authentication.MyAuthServer.java
@Override public User userSignIn(String email, String pass, String authType, Context context) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(SERVER_URL); httpPost.addHeader("Content-Type", "application/json"); UserReq userReq = new UserReq(REST_API_KEY, email, pass); String user = new Gson().toJson(userReq); //for security reasons it will be good to encrypt or hash users email and password; httpPost.addHeader("X-MPAGE-Data", user); try {/* w w w .ja v a 2 s . c o m*/ //HttpResponse response = httpClient.execute(httpPost); //String responseString = EntityUtils.toString(response.getEntity()); // // if (response.getStatusLine().getStatusCode() != HttpURLConnection.HTTP_OK) { // COhaveEuError error = new Gson().fromJson(responseString, COhaveEuError.class); // throw new Exception("Error during log in [" + error.code + "] - " + error.error); // } // // User createdUser = new Gson().fromJson(responseString, User.class); return new User(1, email, "John", "Doe", email, "gg54434cDG"); } catch (com.google.gson.JsonIOException ex) { ex.printStackTrace(); throw new Exception("Wrong answer from server. Try again later. (ERR124)"); } catch (com.google.gson.JsonSyntaxException ex) { ex.printStackTrace(); throw new Exception("Wrong answer from server. Try again later. (ERR125)"); } // catch (IOException e) { // e.printStackTrace(); // throw new Exception("Chyba pri spojeni so serverom. Skontrolujte internetove pripojenie. (ERR123)"); // } }
From source file:de.devbliss.apitester.factory.impl.DefaultPostFactory.java
public HttpPost createPostRequest(URI uri, Object payload) throws IOException { HttpPost request = new HttpPost(uri); if (payload != null) { request.setEntity(entityBuilder.buildEntity(payload)); }/* w ww . j a va 2 s. com*/ return request; }
From source file:org.rapidoid.http.HTTP.java
public static byte[] post(String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files) throws IOException, ClientProtocolException { headers = U.safe(headers);//from w w w . ja v a 2s .c o m data = U.safe(data); files = U.safe(files); CloseableHttpClient client = client(uri); try { HttpPost httppost = new HttpPost(uri); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { ContentType contentType = ContentType.create("application/octet-stream"); String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, contentType, filename); } for (Entry<String, String> entry : data.entrySet()) { ContentType contentType = ContentType.create("text/plain", "UTF-8"); builder = builder.addTextBody(entry.getKey(), entry.getValue(), contentType); } httppost.setEntity(builder.build()); for (Entry<String, String> e : headers.entrySet()) { httppost.addHeader(e.getKey(), e.getValue()); } Log.info("Starting HTTP POST request", "request", httppost.getRequestLine()); CloseableHttpResponse response = client.execute(httppost); try { int statusCode = response.getStatusLine().getStatusCode(); U.must(statusCode == 200, "Expected HTTP status code 200, but found: %s", statusCode); InputStream resp = response.getEntity().getContent(); return IOUtils.toByteArray(resp); } finally { response.close(); } } finally { client.close(); } }