List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler
BasicResponseHandler
From source file:fast.servicescreen.server.RequestServiceImpl.java
@Override public String sendHttpRequest_DELETE(String url, HashMap<String, String> headers, String body) { //create client and method appending to url DefaultHttpClient httpclient_DELETE = new DefaultHttpClient(); httpdelete = new HttpDelete(url); //add all headers if (headers != null) { for (Iterator<String> iterator = headers.keySet().iterator(); iterator.hasNext();) { String tmpKey = (String) iterator.next(); String tmpVal = headers.get(tmpKey); httpdelete.addHeader(tmpKey, tmpVal); }//from www . j av a 2 s . c o m } // Create response handler responseHandler = new BasicResponseHandler(); try { // send the POST request responseBody = httpclient_DELETE.execute(httpdelete, responseHandler); } catch (Exception e) { e.printStackTrace(); responseBody = "-1"; } return responseBody; }
From source file:com.comcast.dawg.pound.DawgPoundIT.java
/** * This method tests the @link{DawgPound#reserve()} API with invalid expiration, and verifies * that the response is false.// w w w . java 2 s .c o m */ @Test(groups = "rest") public void reserveWithInvalidExpirationTest() throws ClientProtocolException, IOException { String deviceId = MetaStbBuilder.getUID(UID_PREF); addStb(deviceId, mac); String token = "xyz"; long exp = System.currentTimeMillis() - RESERVE_EXPIRATION_TIME_OFFSET; String expiration = String.valueOf(exp); // less than current time String url = BASE_URL + "reserve/override/" + token + "/" + invalidDeviceId + "/" + expiration; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); Assert.assertNotNull(responseBody); Assert.assertTrue(responseBody.contains("false")); responseBody = isReserved(deviceId); Assert.assertTrue(!responseBody.contains(token)); }
From source file:com.haulmont.restapi.idp.IdpAuthController.java
@Nullable protected IdpSession getIdpSession(String idpTicket) throws InvalidGrantException { String idpBaseURL = this.idpBaseURL; if (!idpBaseURL.endsWith("/")) { idpBaseURL += "/"; }// w w w . j a va 2 s. com String idpTicketActivateUrl = idpBaseURL + "service/activate"; HttpPost httpPost = new HttpPost(idpTicketActivateUrl); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( Arrays.asList(new BasicNameValuePair("serviceProviderTicket", idpTicket), new BasicNameValuePair("trustedServicePassword", idpTrustedServicePassword)), StandardCharsets.UTF_8); httpPost.setEntity(formEntity); HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(); HttpClient client = HttpClientBuilder.create().setConnectionManager(connectionManager).build(); String idpResponse; try { HttpResponse httpResponse = client.execute(httpPost); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 410) { // used old ticket return null; } if (statusCode != 200) { throw new RuntimeException("Idp respond with status " + statusCode); } idpResponse = new BasicResponseHandler().handleResponse(httpResponse); } catch (IOException e) { throw new RuntimeException("Unable to connect to IDP", e); } finally { connectionManager.shutdown(); } IdpSession session; try { session = new Gson().fromJson(idpResponse, IdpSession.class); } catch (JsonSyntaxException e) { throw new RuntimeException("Unable to parse idp response", e); } return session; }
From source file:com.base.httpclient.HttpJsonClient.java
/** * post// ww w.j a va 2s . c om * * @param url * URL * @param data * * @return * @throws ClientProtocolException * @throws IOException */ public static String post(String url, String data) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httpPost = new HttpPost(url); if (data != null) { ByteArrayEntity mult = new ByteArrayEntity(data.getBytes("UTF-8")); httpPost.setEntity(mult); } log.debug("begin to post url:" + url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); return httpclient.execute(httpPost, responseHandler); } finally { httpclient.getConnectionManager().shutdown(); } }
From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java
private boolean oauthTokenAccess(OAuthToken token) { boolean bstate = false; try {/* w w w . java 2 s . c o m*/ // /oauth/access-token?client_id={0}&grant_type=authorization_code&code={1} Object[] arguments = { this.loginInfo.getCredentials().oauthAppId, token.code, }; String sAccessTokenUri = MessageFormat.format(this.loginInfo.getCredentials().oauthAccessTokenUri, arguments); final HttpGet hget = new HttpGet(this.urlBase + sAccessTokenUri); HttpContext context = new BasicHttpContext(); HttpResponse oauthResponse = getClient().execute(hget, context); // if the OAuth page retrieval failed throw an exception if ((oauthResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) && !("application/json".equals(oauthResponse.getEntity().getContentType().getValue()))) { throw new IOException(oauthResponse.getStatusLine().toString()); } // consume the response ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = responseHandler.handleResponse(oauthResponse); HashMap<String, String> jsonTokens = parseJSonStream(responseBody); jsonTokens.put("authorization_code", token.getCode()); jsonTokens.put("authorization_state", token.getState()); this.writeOauthProperties(jsonTokens); consumeContent(oauthResponse.getEntity()); bstate = true; } catch (IOException ex) { log.error("Error while getting access token", ex); } return bstate; }
From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java
/** * Test run.//from ww w . ja v a2 s .co m * * @param endPoint the end point * @param fileId the file id * @param testList the test list * @param client the client (optional) * @return the string * @throws IOException Signals that an I/O exception has occurred. * @throws JSONException the JSON exception */ private static String testRun(String endPoint, String fileId, List<String> testList, String testTitle, CloseableHttpClient client) throws IOException, JSONException { boolean close = false; if (client == null) { client = HttpClients.createDefault(); close = true; } try { HttpPost request = new HttpPost(endPoint + TestRuns_URL); JSONObject json = new JSONObject(); JSONArray tests = new JSONArray(); JSONObject argumets = new JSONObject(); JSONObject testObject = new JSONObject(); json.put("label", "TEST " + testTitle + " - " + System.currentTimeMillis()); json.put("executableTestSuiteIds", tests); json.put("argumets", argumets); json.put("testObject", testObject); for (String test : testList) { tests.put(test); } argumets.put("files_to_test", ".*"); argumets.put("tests_to_execute", ".*"); testObject.put("id", fileId); StringEntity entity = new StringEntity(json.toString()); request.setEntity(entity); request.setHeader("Content-type", ACCEPT); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Accept", ACCEPT); HttpResponse response; response = client.execute(request); if (response.getStatusLine().getStatusCode() == 201) { ResponseHandler<String> handler = new BasicResponseHandler(); String body = handler.handleResponse(response); JSONObject jsonRoot = new JSONObject(body); String testId = jsonRoot.getJSONObject("EtfItemCollection").getJSONObject("testRuns") .getJSONObject("TestRun").getString("id"); return testId; } else { Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: " + response.getStatusLine().getStatusCode() + " for " + TestRuns_URL); return null; } } catch (Exception e) { Log.error(Log.SERVICE, "Exception in INSPIRE service: " + endPoint, e); return null; } finally { if (close) { try { client.close(); } catch (IOException e) { Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e); } } } }
From source file:ti.modules.titanium.geolocation.GeolocationModule.java
@Override public boolean handleMessage(final Message msg) { if (msg.what == MSG_LOOKUP) { AsyncTask<Object, Void, Integer> task = new AsyncTask<Object, Void, Integer>() { @Override/* w ww . j a v a 2 s . c o m*/ protected Integer doInBackground(Object... args) { try { String url = (String) args[0]; String direction = (String) args[1]; KrollCallback callback = (KrollCallback) args[2]; if (DBG) { Log.d(LCAT, "GEO URL: " + url); } HttpGet httpGet = new HttpGet(url); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000); // TODO use property // HttpConnectionParams.setSoTimeout(httpParams, 15000); // //TODO use property HttpClient client = new DefaultHttpClient(httpParams); ResponseHandler<String> responseHandler = new BasicResponseHandler(); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); String response = client.execute(httpGet, responseHandler); if (DBG) { Log.i(LCAT, "Received Geo: " + response); } KrollDict event = null; if (response != null) { try { JSONObject r = new JSONObject(response); if (r.getBoolean("success")) { if (direction.equals("r")) { event = buildReverseResponse(r); } else { event = buildForwardResponse(r); } } else { event = new KrollDict(); KrollDict err = new KrollDict(); String errorCode = r.getString("errorcode"); err.put("message", "Unable to resolve message: Code (" + errorCode + ")"); err.put("code", errorCode); event.put("error", err); } } catch (JSONException e) { Log.e(LCAT, "Error converting geo response to JSONObject: " + e.getMessage(), e); } } if (event != null) { event.put("source", this); callback.callAsync(event); } } catch (Throwable t) { Log.e(LCAT, "Error retrieving geocode information: " + t.getMessage(), t); } return -1; } }; task.execute(msg.getData().getString("url"), msg.getData().getString("direction"), msg.obj); return true; } return super.handleMessage(msg); }
From source file:org.labkey.freezerpro.export.FreezerProExport.java
/** * Tests the connection configuration//ww w . j a v a2 s. com * @return * @throws ValidationException */ public void testConnection() throws ValidationException { HttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(getConfig().getBaseServerUrl()); try { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("method", "search_samples")); params.add(new BasicNameValuePair("username", getConfig().getUsername())); params.add(new BasicNameValuePair("password", getConfig().getPassword())); params.add(new BasicNameValuePair("query", "")); params.add(new BasicNameValuePair("limit", "1")); post.setEntity(new UrlEncodedFormEntity(params)); ResponseHandler<String> handler = new BasicResponseHandler(); HttpResponse response = client.execute(post); StatusLine status = response.getStatusLine(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { ExportSamplesResponse samplesResponse = new ExportSamplesResponse(this, handler.handleResponse(response), status.getStatusCode(), null); samplesResponse.loadData(); } else throw new ValidationException( "Attempted connection to the FreezerPro server failed with a status code of: " + response.getStatusLine().getStatusCode()); } catch (Exception e) { throw new ValidationException(e.getMessage()); } }
From source file:org.openiot.gsn.utils.VSMonitor.java
public static void readStatus(GSNSessionAddress gsnSessionAddress) throws Exception { String httpAddress = gsnSessionAddress.getURL(); DefaultHttpClient client = new DefaultHttpClient(); if (gsnSessionAddress.needsPassword()) { client.getCredentialsProvider().setCredentials( new AuthScope(gsnSessionAddress.getHost(), gsnSessionAddress.getPort()/*, GSN_REALM*/), new UsernamePasswordCredentials(gsnSessionAddress.getUsername(), gsnSessionAddress.getPassword())); }/*w w w .j a v a2s. c o m*/ logger.warn("Querying server: " + httpAddress); HttpGet get = new HttpGet(httpAddress); try { // execute the GET, getting string directly ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(get, responseHandler); parseXML(responseBody); } catch (HttpResponseException e) { errorsBuffer.append("HTTP 401 Authentication Needed for : ").append(httpAddress).append("\n"); } catch (UnknownHostException e) { errorsBuffer.append("Unknown host: ").append(httpAddress).append("\n"); nHostsDown++; } catch (ConnectException e) { errorsBuffer.append("Connection refused to host: ").append(httpAddress).append("\n"); nHostsDown++; } finally { // release any connection resources used by the method client.getConnectionManager().shutdown(); } }
From source file:imageLines.ImageHelpers.java
/**Read a jpeg image from a url into a BufferedImage*/ public static BufferedImage readAsBufferedImage(String imageURLString, String user, String pass) { InputStream i = null;//from w ww. ja va 2 s.c om try { /* URLConnection conn=imageURL.openConnection(); String userPassword=user+":"+ pass; String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes()); conn.setRequestProperty ("Authorization", "Basic " + encoding);*/ DefaultHttpClient httpclient = new DefaultHttpClient(); ResponseHandler<String> responseHandler = new BasicResponseHandler(); httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(user, pass)); HttpGet httpget = new HttpGet(imageURLString); System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity en = response.getEntity(); Header[] h = response.getAllHeaders(); for (int c = 0; c < h.length; c++) System.out.print(h[c].getName() + ":" + h[c].getValue() + "\n"); i = response.getEntity().getContent(); //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(i); BufferedImage bi = ImageIO.read(i);//decoder.decodeAsBufferedImage(); return bi; } catch (Exception e) { System.out.println(e); return null; } finally { try { if (i != null) i.close(); } catch (IOException ex) { } } }