List of usage examples for org.apache.http.client ResponseHandler ResponseHandler
ResponseHandler
From source file:edu.se.ustc.ClientWithResponseHandler.java
public List<BusRouteInfo> run(String URL) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); List<BusRouteInfo> bsrList = new ArrayList<BusRouteInfo>(); try {//from ww w . ja va 2s . c o m HttpGet httpget = new HttpGet(URL); //debug //System.out.println("Executing request " + httpget.getRequestLine()); // Create a custom response handler ResponseHandler<String> responseHandler = new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpclient.execute(httpget, responseHandler); //System.out.println("----------------------------------------"); //System.out.println(responseBody); String str = responseBody.substring(responseBody.indexOf("table"), responseBody.lastIndexOf("table")); //debug //System.out.println(str); BusRouteInfo binfo = new BusRouteInfo(); bsrList = binfo.getBusRouteInfoList(str); //debug, print all infomation //binfo.printBusRouteInfo(bsrList); //select the db //dbUtil db = new dbUtil(); //result=db.executeQuery("SELECT * FROM station_stats"); // if(result!=null) // System.out.println(result.getString(1)); } finally { httpclient.close(); } return bsrList; }
From source file:org.bireme.cl.CheckUrl.java
public static int check(final String url, final boolean checkOnlyHeader) { if (url == null) { throw new NullPointerException(); }//from w w w .j av a 2 s.c o m final CloseableHttpClient httpclient = HttpClients.createDefault(); int responseCode = -1; try { final HttpRequestBase httpX = checkOnlyHeader ? new HttpHead(fixUrl(url)) : new HttpGet(fixUrl(url)); //final HttpHead httpX = new HttpHead(fixUrl(url)); // Some servers return 500 //final HttpGet httpX = new HttpGet(fixUrl(url)); httpX.setConfig(CONFIG); httpX.setHeader(new BasicHeader("User-Agent", "Wget/1.16.1 (linux-gnu)")); httpX.setHeader(new BasicHeader("Accept", "*/*")); httpX.setHeader(new BasicHeader("Accept-Encoding", "identity")); httpX.setHeader(new BasicHeader("Connection", "Keep-Alive")); // Create a custom response handler final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() { @Override public Integer handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { return response.getStatusLine().getStatusCode(); } }; responseCode = httpclient.execute(httpX, responseHandler); } catch (Exception ex) { responseCode = getExceptionCode(ex); } finally { try { httpclient.close(); } catch (Exception ioe) { System.err.println(ioe.getMessage()); } } return (((responseCode == 403) || (responseCode == 500)) && checkOnlyHeader) ? check(url, false) : responseCode; }
From source file:com.quartzdesk.executor.core.job.UrlInvokerJob.java
@Override protected void executeJob(final JobExecutionContext context) throws JobExecutionException { log.debug("Inside job: {}", context.getJobDetail().getKey()); JobDataMap jobDataMap = context.getMergedJobDataMap(); // url (required) final String url = jobDataMap.getString(JDM_KEY_URL); if (url == null) { throw new JobExecutionException("Missing required '" + JDM_KEY_URL + "' job data map parameter."); }// ww w . j a va 2 s . c o m // username (optional) String username = jobDataMap.getString(JDM_KEY_USERNAME); // password (optional) String password = jobDataMap.getString(JDM_KEY_PASSWORD); CloseableHttpClient httpClient; if (username != null && password != null) { // use HTTP basic authentication CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); } else { // use no HTTP authentication httpClient = HttpClients.custom().build(); } try { HttpPost httpPost = new HttpPost(url); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse httpResponse) throws IOException { int status = httpResponse.getStatusLine().getStatusCode(); //context.setResult( Integer.toString( status ) ); if (status >= 200 && status < 300) { HttpEntity entity = httpResponse.getEntity(); return entity == null ? null : EntityUtils.toString(entity); } else { throw new ClientProtocolException( "URL: " + url + " returned unexpected response status code: " + status); } } }; log.debug("HTTP request line: {}", httpPost.getRequestLine()); log.info("Invoking target URL: {}", url); String responseText = httpClient.execute(httpPost, responseHandler); log.debug("Response text: {}", responseText); if (!responseText.trim().isEmpty()) { /* * We use the HTTP response text as the Quartz job execution result. This code can then be easily * viewed in the Execution History in the QuartzDesk GUI and it can be, for example, used to trigger * execution notifications. */ context.setResult(responseText); } } catch (IOException e) { throw new JobExecutionException("Error invoking URL: " + url, e); } finally { try { httpClient.close(); } catch (IOException e) { log.error("Error closing HTTP client.", e); } } }
From source file:Main.java
public static ResponseHandler<String> GetResponseHandlerInstance(final Handler handler) { final ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override//ww w .j ava 2 s .c om public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { Message message = handler.obtainMessage(); Bundle bundle = new Bundle(); StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { try { result = InputStreamToString(entity.getContent()); bundle.putString("RESPONSE", result); message.setData(bundle); handler.sendMessage(message); } catch (IOException e) { bundle.putString("RESPONSE", "Error - " + e.getMessage()); message.setData(bundle); handler.sendMessage(message); } } else { bundle.putString("RESPONSE", "Error - " + response.getStatusLine().getReasonPhrase()); message.setData(bundle); handler.sendMessage(message); } return result; } }; return responseHandler; }
From source file:org.jwebsocket.sso.HTTPSupport.java
/** * * @param aURL//ww w. j av a 2s . c o m * @param aMethod * @param aHeaders * @param aPostBody * @param aTimeout * @return */ public static String request(String aURL, String aMethod, Map<String, String> aHeaders, String aPostBody, long aTimeout) { if (mLog.isDebugEnabled()) { mLog.debug("Requesting (" + aMethod + ") '" + aURL + "', timeout: " + aTimeout + "ms, Headers: " + aHeaders + ", Body: " + (null != aPostBody ? "'" + aPostBody.replace("\n", "\\n").replace("\r", "\\r") + "'" : "[null]")); } String lResponse = "{\"code\": -1, \"msg\": \"undefined\""; try { KeyStore lTrustStore = KeyStore.getInstance(KeyStore.getDefaultType()); lTrustStore.load(null, null); // Trust own CA and all self-signed certs SSLContext lSSLContext = SSLContexts.custom() .loadTrustMaterial(lTrustStore, new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory lSSLFactory = new SSLConnectionSocketFactory(lSSLContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient lHTTPClient = HttpClients.custom().setSSLSocketFactory(lSSLFactory).build(); HttpUriRequest lRequest; if ("POST".equals(aMethod)) { lRequest = new HttpPost(aURL); ((HttpPost) lRequest).setEntity(new ByteArrayEntity(aPostBody.getBytes("UTF-8"))); } else { lRequest = new HttpGet(aURL); } for (Map.Entry<String, String> lEntry : aHeaders.entrySet()) { lRequest.setHeader(lEntry.getKey(), lEntry.getValue()); } // System.out.println("Executing request " + lRequest.getRequestLine()); // Create a custom response handler ResponseHandler<String> lResponseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse lResponse) throws ClientProtocolException, IOException { int lStatus = lResponse.getStatusLine().getStatusCode(); HttpEntity lEntity = lResponse.getEntity(); return lEntity != null ? EntityUtils.toString(lEntity) : null; // if (lStatus >= 200 && lStatus < 300) { // HttpEntity entity = lResponse.getEntity(); // return entity != null ? EntityUtils.toString(entity) : null; // } else { // throw new ClientProtocolException("Unexpected response status: " + lStatus); // } } }; long lStartedAt = System.currentTimeMillis(); lResponse = lHTTPClient.execute(lRequest, lResponseHandler); if (mLog.isDebugEnabled()) { mLog.debug("Response (" + (System.currentTimeMillis() - lStartedAt) + "ms): '" + lResponse.replace("\n", "\\n").replace("\r", "\\r") + "'"); } return lResponse; } catch (Exception lEx) { String lMsg = "{\"code\": -1, \"msg\": \"" + lEx.getClass().getSimpleName() + " at http request: " + lEx.getMessage() + "\"}"; mLog.error(lEx.getClass().getSimpleName() + ": " + lEx.getMessage() + ", returning: " + lMsg); lResponse = lMsg; return lResponse; } }
From source file:com.android.sslload.SslLoad.java
public void run() { boolean error = false; while (true) { synchronized (this) { while (!running) { try { this.wait(); } catch (InterruptedException e) { /* ignored */ } }//from w ww . j av a 2 s .c om } AndroidHttpClient client = AndroidHttpClient .newInstance("Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101"); try { // Cert. is for "www.google.com", not "google.com". String url = error ? "https://google.com/" : "https://www.google.com"; client.execute(new HttpGet(url), new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) { /* ignore */ return null; } }); Log.i(TAG, "Request succeeded."); } catch (IOException e) { Log.w(TAG, "Request failed.", e); } client.close(); try { Thread.sleep(1000); } catch (InterruptedException e) { /* ignored */ } error = !error; } }
From source file:org.skfiy.typhon.spi.auth.p.QihooAuthenticator.java
@Override public UserInfo authentic(OAuth2 oauth) { CloseableHttpClient hc = HC_BUILDER.build(); HttpPost httpPost = new HttpPost("https://openapi.360.cn/user/me"); List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("access_token", oauth.getCode())); try {//from ww w. ja v a2 s .c o m httpPost.setEntity(new UrlEncodedFormEntity(nvps)); JSONObject json = hc.execute(httpPost, new ResponseHandler<JSONObject>() { @Override public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException { String str = StreamUtils.copyToString(response.getEntity().getContent(), StandardCharsets.UTF_8); return JSON.parseObject(str); } }); if (json.containsKey("error_code")) { throw new OAuth2Exception(json.getString("error_code")); } UserInfo info = new UserInfo(); info.setUsername(getPlatform().getLabel() + "-" + json.getString("name")); info.setPlatform(getPlatform()); return info; } catch (IOException ex) { throw new OAuth2Exception("qihoo?", ex); } finally { try { hc.close(); } catch (IOException ex) { } } }
From source file:com.jonbanjo.cups.operations.HttpPoster.java
static OperationResult sendRequest(URL url, ByteBuffer ippBuf, InputStream documentStream, final AuthInfo auth) throws IOException { final OperationResult opResult = new OperationResult(); if (ippBuf == null) { return null; }// w w w . j a va 2 s . c o m if (url == null) { return null; } DefaultHttpClient client = new DefaultHttpClient(); // will not work with older versions of CUPS! client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1); client.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT); client.getParams().setParameter("http.connection.timeout", CONNECTION_TIMEOUT); client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); client.getParams().setParameter("http.method.response.buffer.warnlimit", new Integer(8092)); // probabaly not working with older CUPS versions client.getParams().setParameter("http.protocol.expect-continue", Boolean.valueOf(true)); HttpPost httpPost; try { httpPost = new HttpPost(url.toURI()); } catch (Exception e) { System.out.println(e.toString()); return null; } httpPost.getParams().setParameter("http.socket.timeout", SOCKET_TIMEOUT); byte[] bytes = new byte[ippBuf.limit()]; ippBuf.get(bytes); ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes); // If we need to send a document, concatenate InputStreams InputStream inputStream = headerStream; if (documentStream != null) { inputStream = new SequenceInputStream(headerStream, documentStream); } // set length to -1 to advice the entity to read until EOF InputStreamEntity requestEntity = new InputStreamEntity(inputStream, -1); requestEntity.setContentType(IPP_MIME_TYPE); httpPost.setEntity(requestEntity); if (auth.reason == AuthInfo.AUTH_REQUESTED) { AuthHeader.makeAuthHeader(httpPost, auth); if (auth.reason == AuthInfo.AUTH_OK) { httpPost.addHeader(auth.getAuthHeader()); //httpPost.addHeader("Authorization", "Basic am9uOmpvbmJveQ=="); } } ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { @Override public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { if (response.getStatusLine().getStatusCode() == 401) { auth.setHttpHeader(response.getFirstHeader("WWW-Authenticate")); } else { auth.reason = AuthInfo.AUTH_OK; } HttpEntity entity = response.getEntity(); opResult.setHttResult(response.getStatusLine().toString()); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; if (url.getProtocol().equals("https")) { Scheme scheme = JfSSLScheme.getScheme(); if (scheme == null) return null; client.getConnectionManager().getSchemeRegistry().register(scheme); } byte[] result = client.execute(httpPost, handler); //String test = new String(result); IppResponse ippResponse = new IppResponse(); opResult.setIppResult(ippResponse.getResponse(ByteBuffer.wrap(result))); opResult.setAuthInfo(auth); client.getConnectionManager().shutdown(); return opResult; }
From source file:org.eclipse.vorto.repository.RestClient.java
@SuppressWarnings("restriction") public Attachment executeGetAttachment(String query) throws ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.custom().build(); HttpUriRequest request = RequestBuilder.get().setConfig(createProxyConfiguration()) .setUri(createQuery(query)).build(); return client.execute(request, new ResponseHandler<Attachment>() { @Override/*from w w w .j a v a 2 s .c o m*/ public Attachment handleResponse(HttpResponse response) throws ClientProtocolException, IOException { String content_disposition = response.getFirstHeader("Content-Disposition").getValue(); String filename = content_disposition .substring(content_disposition.indexOf("filename = ") + "filename = ".length()); long length = response.getEntity().getContentLength(); String type = response.getEntity().getContentType().toString(); byte[] content = IOUtils.toByteArray(response.getEntity().getContent()); return new Attachment(filename, length, type, content); } }); }
From source file:com.unifonic.sdk.HttpSender.java
public OTSRestResponse requestDefault(String url, HttpEntity data) throws IOException { HttpPost post = new HttpPost(url); post.setEntity(data);/*from ww w .j av a 2 s .com*/ ResponseHandler<OTSRestResponse> rh = new ResponseHandler<OTSRestResponse>() { @Override public OTSRestResponse handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity == null) { throw new ClientProtocolException("Response contains no content"); } OTSRestResponse orr = new OTSRestResponse(); orr.setStatusCode(response.getStatusLine().getStatusCode()); orr.setReasonPhrase(response.getStatusLine().getReasonPhrase()); String respContent = InputStreamUtil.readString(entity.getContent()); log.debug("Response:" + orr.getStatusCode() + ":" + orr.getReasonPhrase() + ":" + respContent); if (orr.getStatusCode() == 400) { respContent = respContent.replace(",\"data\":[]", ""); } orr.setData(respContent); return orr; } }; OTSRestResponse execute = httpClient.execute(post, rh); return execute; }