List of usage examples for org.apache.http.protocol ExecutionContext HTTP_REQUEST
String HTTP_REQUEST
To view the source code for org.apache.http.protocol ExecutionContext HTTP_REQUEST.
Click Source Link
From source file:it.staiger.jmeter.protocol.http.sampler.HTTPHC4DynamicFilePost.java
/** * Parses the result and fills the SampleResult with its info * @param httpRequest the executed request * @param localContext the Http context which was used * @param res the SampleResult which is to be filled * @param httpResponse the response which is to be parsed * @throws IllegalStateException// ww w . j av a2s . c o m * @throws IOException */ private void parseResponse(HttpRequestBase httpRequest, HttpContext localContext, HTTPSampleResult res, HttpResponse httpResponse) throws IllegalStateException, IOException { // Needs to be done after execute to pick up all the headers final HttpRequest request = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); // We've finished with the request, so we can add the LocalAddress to it for display final InetAddress localAddr = (InetAddress) httpRequest.getParams() .getParameter(ConnRoutePNames.LOCAL_ADDRESS); if (localAddr != null) { request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString()); } res.setRequestHeaders(getConnectionHeaders(request)); Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE); if (contentType != null) { String ct = contentType.getValue(); res.setContentType(ct); res.setEncodingAndType(ct); } HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); res.setResponseData(readResponse(res, instream, (int) entity.getContentLength())); } res.sampleEnd(); // Done with the sampling proper. currentRequest = null; // Now collect the results into the HTTPSampleResult: StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); res.setResponseCode(Integer.toString(statusCode)); res.setResponseMessage(statusLine.getReasonPhrase()); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseHeaders(getResponseHeaders(httpResponse)); if (res.isRedirect()) { final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION); if (headerLocation == null) { // HTTP protocol violation, but avoids NPE throw new IllegalArgumentException( "Missing location header in redirect for " + httpRequest.getRequestLine()); } String redirectLocation = headerLocation.getValue(); res.setRedirectLocation(redirectLocation); } // record some sizes to allow HTTPSampleResult.getBytes() with different options HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS); long headerBytes = res.getResponseHeaders().length() // condensed length (without \r) + httpResponse.getAllHeaders().length // Add \r for each header + 1 // Add \r for initial header + 2; // final \r\n before data long totalBytes = metrics.getReceivedBytesCount(); res.setHeadersSize((int) headerBytes); res.setBodySize((int) (totalBytes - headerBytes)); if (log.isDebugEnabled()) { log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize() + " Total=" + (res.getHeadersSize() + res.getBodySize())); } // If we redirected automatically, the URL may have changed if (getAutoRedirects()) { HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); URI redirectURI = req.getURI(); if (redirectURI.isAbsolute()) { res.setURL(redirectURI.toURL()); } else { res.setURL(new URL(new URL(target.toURI()), redirectURI.toString())); } } }
From source file:net.sourceforge.kalimbaradio.androidapp.service.RESTMusicService.java
private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) { HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // Sometimes the request doesn't contain the "http://host" part so we // must take from the HttpHost object. String redirectedUrl;/* w w w.java2s . co m*/ if (request.getURI().getScheme() == null) { redirectedUrl = host.toURI() + request.getURI(); } else { redirectedUrl = request.getURI().toString(); } redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/")); redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/")); LOG.info(redirectFrom + " redirects to " + redirectTo); redirectionLastChecked = System.currentTimeMillis(); redirectionNetworkType = getCurrentNetworkType(context); }
From source file:cz.cesnet.shongo.connector.device.CiscoMCUConnector.java
/** * Try to login for {@link #httpClient}/*w ww. java 2 s. c o m*/ * * @throws CommandException when login fails */ private void loginHttp() throws CommandException { try { HttpPost request = new HttpPost(getDeviceHttpUrl("/login_change.html").toURI()); List<NameValuePair> parameters = new ArrayList<NameValuePair>(2); parameters.add(new BasicNameValuePair("user_name", authUsername)); parameters.add(new BasicNameValuePair("password", authPassword)); parameters.add(new BasicNameValuePair("ok", "OK")); request.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); HttpContext context = new BasicHttpContext(); HttpResponse response = httpClient.execute(request, context); HttpRequest responseRequest = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); StatusLine responseStatusLine = response.getStatusLine(); if (responseStatusLine.getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException("Wrong status " + responseStatusLine); } String responseRequestUrl = responseRequest.getRequestLine().getUri(); if (responseRequestUrl.startsWith("/index.html") || responseRequestUrl.equals("/")) { logger.info("Http login successful."); } else { throw new RuntimeException("Wrong response url " + responseRequestUrl); } } catch (Exception exception) { throw new CommandException("Http login failed", exception); } }
From source file:com.tandong.sa.aq.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }/*from w w w. j a va2 s .c o m*/ if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (timeout > 0) { AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT); hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = client.execute(hr, context); byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); Header[] hs = response.getAllHeaders(); HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length); for (Header h : hs) { responseHeaders.put(h.getName(), h.getValue()); } setResponseHeaders(responseHeaders); File file = null; if (code < 200 || code >= 300) { try { if (entity != null) { InputStream is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } //AQUtility.time("copy"); copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength()); //AQUtility.timeEnd("copy", 0); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || file.length() == 0) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }
From source file:com.androidquery.callback.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }//from w w w. j a v a2s .co m if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (timeout > 0) { hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = null; try { response = client.execute(hr, context); } catch (HttpHostConnectException e) { //if proxy is used, automatically retry without proxy if (proxy != null) { AQUtility.debug("proxy failed, retrying without proxy"); hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); response = client.execute(hr, context); } else { throw e; } } byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); File file = null; if (code < 200 || code >= 300) { InputStream is = null; try { if (entity != null) { is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } finally { AQUtility.close(is); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } //AQUtility.time("copy"); copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength()); //AQUtility.timeEnd("copy", 0); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || file.length() == 0) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }
From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }// w w w.j a v a 2 s .c om if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && ((headers == null) || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) { hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } if (timeout > 0) { hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); // CookieStore cookieStore = new BasicCookieStore(); // context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = null; try { //response = client.execute(hr, context); response = execute(hr, client, context); getCookie(client); } catch (HttpHostConnectException e) { //if proxy is used, automatically retry without proxy if (proxy != null) { AQUtility.debug("proxy failed, retrying without proxy"); hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); //response = client.execute(hr, context); response = execute(hr, client, context); } else { throw e; } } byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); File file = null; if ((code < 200) || (code >= 300)) { InputStream is = null; try { if (entity != null) { is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } finally { AQUtility.close(is); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } is = entity.getContent(); if ("gzip".equalsIgnoreCase(getEncoding(entity))) { is = new GZIPInputStream(is); } copy(is, os, (int) entity.getContentLength()); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || (file.length() == 0)) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }
From source file:com.appbase.androidquery.callback.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }/*from ww w. ja v a 2s .c o m*/ if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); if (timeout > 0) { hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = null; try { //response = client.execute(hr, context); response = execute(hr, client, context); } catch (HttpHostConnectException e) { //if proxy is used, automatically retry without proxy if (proxy != null) { AQUtility.debug("proxy failed, retrying without proxy"); hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); //response = client.execute(hr, context); response = execute(hr, client, context); } else { throw e; } } byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); File file = null; if (code < 200 || code >= 300) { InputStream is = null; try { if (entity != null) { is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } finally { AQUtility.close(is); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } is = entity.getContent(); if ("gzip".equalsIgnoreCase(getEncoding(entity))) { is = new GZIPInputStream(is); } copy(is, os, (int) entity.getContentLength()); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || file.length() == 0) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }
From source file:github.daneren2005.dsub.service.RESTMusicService.java
private void detectRedirect(String originalUrl, Context context, HttpContext httpContext) { HttpUriRequest request = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost host = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // Sometimes the request doesn't contain the "http://host" part String redirectedUrl;/*from w w w . j a v a 2 s. co m*/ if (request.getURI().getScheme() == null) { redirectedUrl = host.toURI() + request.getURI(); } else { redirectedUrl = request.getURI().toString(); } redirectFrom = originalUrl.substring(0, originalUrl.indexOf("/rest/")); redirectTo = redirectedUrl.substring(0, redirectedUrl.indexOf("/rest/")); if (redirectFrom.compareTo(redirectTo) != 0) { Log.i(TAG, redirectFrom + " redirects to " + redirectTo); } redirectionLastChecked = System.currentTimeMillis(); redirectionNetworkType = getCurrentNetworkType(context); }
From source file:com.akop.bach.parser.XboxLiveParser.java
private GameOverviewInfo parseGameOverview(String url) throws IOException, ParserException { String loadUrl = url;/*from w w w. ja v a 2s . co m*/ if (PATTERN_GAME_OVERVIEW_REDIRECTING_URL.matcher(url).find()) { // Redirecting URL; figure out where it's redirecting HttpParams p = mHttpClient.getParams(); try { p.setParameter("http.protocol.max-redirects", 1); HttpGet httpget = new HttpGet(url); HttpContext context = new BasicHttpContext(); HttpResponse response = mHttpClient.execute(httpget, context); HttpEntity entity = response.getEntity(); if (entity != null) entity.consumeContent(); HttpUriRequest request = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); try { loadUrl = new URI(url).resolve(request.getURI()).toString(); } catch (URISyntaxException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); } if (App.getConfig().logToConsole()) App.logv("Redirection URL determined to be " + loadUrl); } finally { p.setParameter("http.protocol.max-redirects", 0); } } String page = getResponse(loadUrl.concat("?NoSplash=1")); GameOverviewInfo overview = new GameOverviewInfo(); Matcher m; if (!(m = PATTERN_GAME_OVERVIEW_TITLE.matcher(page)).find()) throw new ParserException(mContext, R.string.error_no_details_available); overview.Title = htmlDecode(m.group(1)); if ((m = PATTERN_GAME_OVERVIEW_DESCRIPTION.matcher(page)).find()) overview.Description = htmlDecode(m.group(1)); if ((m = PATTERN_GAME_OVERVIEW_MANUAL.matcher(page)).find()) overview.ManualUrl = m.group(1); if ((m = PATTERN_GAME_OVERVIEW_ESRB.matcher(page)).find()) { overview.EsrbRatingDescription = htmlDecode(m.group(1)); overview.EsrbRatingIconUrl = m.group(2); } if ((m = PATTERN_GAME_OVERVIEW_BANNER.matcher(page)).find()) overview.BannerUrl = m.group(1); m = PATTERN_GAME_OVERVIEW_IMAGE.matcher(page); while (m.find()) overview.Screenshots.add(m.group(1)); return overview; }
From source file:org.apache.http.impl.client.DefaultRedirectHandler.java
public boolean isRedirectRequested(final HttpResponse response, final HttpContext context) { Args.notNull(response, "HTTP response"); final int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_TEMPORARY_REDIRECT: final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); final String method = request.getRequestLine().getMethod(); return method.equalsIgnoreCase(HttpGet.METHOD_NAME) || method.equalsIgnoreCase(HttpHead.METHOD_NAME); case HttpStatus.SC_SEE_OTHER: return true; default:/*from w ww . j a v a 2 s .com*/ return false; } //end of switch }