public void execute() { client = new HttpClient(); // if (requestType.equals("GET")) { // Instantiate a GET HTTP method // HttpMethod method = new GetMethod(apiUrl); // if (!authentication.equals("")) { // method.setRequestHeader("Authorization", "basic " + authentication); // } try { int statusCode = client.executeMethod(method); System.out.println("QueryString>>> " + apiUrl); System.out.println("Status Text>>>" + HttpStatus.getStatusText(statusCode)); // Get data as a String System.out.println(method.getResponseBodyAsString()); // OR as a byte array byte[] res = method.getResponseBody(); // write to file FileOutputStream fos = new FileOutputStream("donepage.html"); fos.write(res); // release connection method.releaseConnection(); } catch (IOException e) { e.printStackTrace(); } // } }
public void doRequest( HttpMethod method, __HttpConnectionResponseHandler responseHandler, String url, HashMap<String, String> params) { /* * [ Check network connection state ] */ if (!DeviceUtil.isNetworkAvailable(AppGlobalApplication.getAppGlobalApplicationContext())) { return; } if (method.equals(HttpMethod.GET)) { GetMethodRequestObject requestObject = new GetMethodRequestObject(responseHandler, url, params); requestObject.start(); } else if (method.equals(HttpMethod.POST)) { PostMethodRequestObject requestObject = new PostMethodRequestObject(responseHandler, url, params); requestObject.start(); } }
/* Quick lookahead for the start state looking for a request method or a HTTP version, * otherwise skip white space until something else to parse. */ private boolean quickStart(ByteBuffer buffer) { if (_requestHandler != null) { _method = HttpMethod.lookAheadGet(buffer); if (_method != null) { _methodString = _method.asString(); buffer.position(buffer.position() + _methodString.length() + 1); setState(State.SPACE1); return false; } } else if (_responseHandler != null) { _version = HttpVersion.lookAheadGet(buffer); if (_version != null) { buffer.position(buffer.position() + _version.asString().length() + 1); setState(State.SPACE1); return false; } } // Quick start look while (_state == State.START && buffer.hasRemaining()) { int ch = next(buffer); if (ch > HttpTokens.SPACE) { _string.setLength(0); _string.append((char) ch); setState(_requestHandler != null ? State.METHOD : State.RESPONSE_VERSION); return false; } else if (ch == 0) break; else if (ch < 0) throw new BadMessage(); } return false; }
/** * @param factory the factory used to create InterfaceHttpData * @param request the request to decode * @param charset the charset to use as default * @throws NullPointerException for request or charset or factory * @throws IncompatibleDataDecoderException if the request has no body to decode * @throws ErrorDataDecoderException if the default charset was wrong when decoding or other * errors */ public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request, Charset charset) throws ErrorDataDecoderException, IncompatibleDataDecoderException { if (factory == null) { throw new NullPointerException("factory"); } if (request == null) { throw new NullPointerException("request"); } if (charset == null) { throw new NullPointerException("charset"); } this.request = request; HttpMethod method = request.getMethod(); if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)) { bodyToDecode = true; } this.charset = charset; this.factory = factory; // Fill default values if (this.request.containsHeader(HttpHeaders.Names.CONTENT_TYPE)) { checkMultipart(this.request.getHeader(HttpHeaders.Names.CONTENT_TYPE)); } else { isMultipart = false; } if (!bodyToDecode) { throw new IncompatibleDataDecoderException("No Body to decode"); } if (!this.request.isChunked()) { undecodedChunk = this.request.getContent(); isLastChunk = true; parseBody(); } }
public RequestDispatcher(Iterable<GrizzletHandler> grizzlets) { Map<String, Map<HttpMethod, GrizzletHandler>> modifiableHandlersMap = Maps.newHashMap(); for (GrizzletHandler handler : grizzlets) { Map<HttpMethod, GrizzletHandler> handlerByMethod = modifiableHandlersMap.get(handler.getPath()); if (handlerByMethod == null) { handlerByMethod = Maps.newEnumMap(HttpMethod.class); modifiableHandlersMap.put(handler.getPath(), handlerByMethod); } for (HttpMethod method : handler.getMethods()) { GrizzletHandler alreadyHandler = handlerByMethod.put(method, handler); if (alreadyHandler != null) { throw new IllegalArgumentException( "More than one handler detected for path='" + handler.getPath() + "', method='" + method.name() + '\''); } } } for (Map.Entry<String, Map<HttpMethod, GrizzletHandler>> entry : modifiableHandlersMap.entrySet()) { modifiableHandlersMap.put(entry.getKey(), Collections.unmodifiableMap(entry.getValue())); } handlers = ImmutableMap.copyOf(modifiableHandlersMap); }
static { HttpMethod[] methods = HttpMethod.values(); for (int i = 0; i < methods.length; i++) { HttpMethod method = methods[i]; _methods[i] = method.toString(); } }
String getContent(HttpMethod httpMethod) { StringBuilder contentBuilder = new StringBuilder(); if (isZipContent(httpMethod)) { InputStream is = null; GZIPInputStream gzin = null; InputStreamReader isr = null; BufferedReader br = null; try { is = httpMethod.getResponseBodyAsStream(); gzin = new GZIPInputStream(is); isr = new InputStreamReader( gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // ���ö�ȡ���ı����ʽ���Զ������ br = new BufferedReader(isr); char[] buffer = new char[4096]; int readlen = -1; while ((readlen = br.read(buffer, 0, 4096)) != -1) { contentBuilder.append(buffer, 0, readlen); } } catch (Exception e) { log.error("Unzip fail", e); } finally { try { br.close(); } catch (Exception e1) { // ignore } try { isr.close(); } catch (Exception e1) { // ignore } try { gzin.close(); } catch (Exception e1) { // ignore } try { is.close(); } catch (Exception e1) { // ignore } } } else { String content = null; try { content = httpMethod.getResponseBodyAsString(); } catch (Exception e) { log.error("Fetch config error:", e); } if (null == content) { return null; } contentBuilder.append(content); } return contentBuilder.toString(); }
private boolean processProxyAuthChallenge(final HttpMethod method) throws MalformedChallengeException, AuthenticationException { AuthState authstate = method.getProxyAuthState(); Map proxyChallenges = AuthChallengeParser.parseChallenges(method.getResponseHeaders(PROXY_AUTH_CHALLENGE)); if (proxyChallenges.isEmpty()) { LOG.debug("Proxy authentication challenge(s) not found"); return false; } AuthScheme authscheme = null; try { authscheme = this.authProcessor.processChallenge(authstate, proxyChallenges); } catch (AuthChallengeException e) { if (LOG.isWarnEnabled()) { LOG.warn(e.getMessage()); } } if (authscheme == null) { return false; } AuthScope authscope = new AuthScope( conn.getProxyHost(), conn.getProxyPort(), authscheme.getRealm(), authscheme.getSchemeName()); if (LOG.isDebugEnabled()) { LOG.debug("Proxy authentication scope: " + authscope); } if (authstate.isAuthAttempted() && authscheme.isComplete()) { // Already tried and failed Credentials credentials = promptForProxyCredentials(authscheme, method.getParams(), authscope); if (credentials == null) { if (LOG.isInfoEnabled()) { LOG.info("Failure authenticating with " + authscope); } return false; } else { return true; } } else { authstate.setAuthAttempted(true); Credentials credentials = this.state.getProxyCredentials(authscope); if (credentials == null) { credentials = promptForProxyCredentials(authscheme, method.getParams(), authscope); } if (credentials == null) { if (LOG.isInfoEnabled()) { LOG.info("No credentials available for " + authscope); } return false; } else { return true; } } }
boolean isZipContent(HttpMethod httpMethod) { if (null != httpMethod.getResponseHeader(Constants.CONTENT_ENCODING)) { String acceptEncoding = httpMethod.getResponseHeader(Constants.CONTENT_ENCODING).getValue(); if (acceptEncoding.toLowerCase().indexOf("gzip") > -1) { return true; } } return false; }
/** * Find a route for method and path. * * @param httpMethod http method. * @param pathInfo path. * @return the route found (null if no route found). */ protected Route findRoute(String httpMethod, String pathInfo) { if (!routes.containsKey(HttpMethod.fromValue(httpMethod))) { return null; } for (Route route : routes.get(HttpMethod.fromValue(httpMethod))) { if (route.isThisPath(pathInfo)) { return route; } } return null; }
private boolean cleanAuthHeaders(final HttpMethod method, final String name) { Header[] authheaders = method.getRequestHeaders(name); boolean clean = true; for (int i = 0; i < authheaders.length; i++) { Header authheader = authheaders[i]; if (authheader.isAutogenerated()) { method.removeRequestHeader(authheader); } else { clean = false; } } return clean; }
private HTTPClientResponseResolver createResponseResolver( final HttpMethod httpMethod, final Status status, final Header[] headers) { try { when(httpMethod.getStatusLine()) .thenReturn( new org.apache.commons.httpclient.StatusLine( String.format("HTTP/1.1 %s %s\r\n", status.getCode(), status.getName()))); } catch (HttpException e) { throw new RuntimeException(e); } when(httpMethod.getStatusCode()).thenReturn(status.getCode()); when(httpMethod.getResponseHeaders()).thenReturn(headers); return new TestableHTTPClientResponseResolver(httpMethod); }
/** * Handles requests with message handler implementation. Previously sets Http request method as * header parameter. * * @param method * @param requestEntity * @return */ private ResponseEntity<String> handleRequestInternal( HttpMethod method, HttpEntity<String> requestEntity) { Map<String, ?> httpRequestHeaders = headerMapper.toHeaders(requestEntity.getHeaders()); Map<String, String> customHeaders = new HashMap<String, String>(); for (Entry<String, List<String>> header : requestEntity.getHeaders().entrySet()) { if (!httpRequestHeaders.containsKey(header.getKey())) { customHeaders.put( header.getKey(), StringUtils.collectionToCommaDelimitedString(header.getValue())); } } HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); UrlPathHelper pathHelper = new UrlPathHelper(); customHeaders.put(CitrusHttpMessageHeaders.HTTP_REQUEST_URI, pathHelper.getRequestUri(request)); customHeaders.put( CitrusHttpMessageHeaders.HTTP_CONTEXT_PATH, pathHelper.getContextPath(request)); String queryParams = pathHelper.getOriginatingQueryString(request); customHeaders.put( CitrusHttpMessageHeaders.HTTP_QUERY_PARAMS, queryParams != null ? queryParams : ""); customHeaders.put(CitrusHttpMessageHeaders.HTTP_REQUEST_METHOD, method.toString()); Message<?> response = messageHandler.handleMessage( MessageBuilder.withPayload(requestEntity.getBody()) .copyHeaders(convertHeaderTypes(httpRequestHeaders)) .copyHeaders(customHeaders) .build()); return generateResponse(response); }
private String getResponse(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(httpMethod.name()); conn.connect(); InputStream is = conn.getInputStream(); return Utils.readInput(is); }
/** * Write http response. * * @param request http request. * @param response http response. * @param handlerResponse response of route handler. * @throws IOException in case of IO error. */ private void writeHttpResponse( HttpServletRequest request, HttpServletResponse response, Response<?> handlerResponse) throws IOException { if (handlerResponse.getStatus() != null) { response.setStatus(handlerResponse.getStatus()); } else if (handlerResponse.getAnswer() == null) { response.setStatus(HttpMethod.fromValue(request.getMethod()).getDefaultStatusWithNoContent()); } else { response.setStatus(HttpMethod.fromValue(request.getMethod()).getDefaultStatus()); } if (handlerResponse.getAnswer() != null) { response.setContentType("application/json"); response.getOutputStream().print(gson.toJson(handlerResponse.getAnswer())); response.getOutputStream().close(); } }
/** * Tests if the {@link HttpMethod method} requires a redirect to another location. * * @param method HTTP method * @return boolean <tt>true</tt> if a retry is needed, <tt>false</tt> otherwise. */ private boolean isRedirectNeeded(final HttpMethod method) { switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: LOG.debug("Redirect required"); if (method.getFollowRedirects()) { return true; } else { return false; } default: return false; } // end of switch }
/** * Fake response * * @param method * @return */ private void fakeResponse(final HttpMethod method) throws IOException, HttpException { // What is to follow is an ugly hack. // I REALLY hate having to resort to such // an appalling trick // The only feasible solution is to split monolithic // HttpMethod into HttpRequest/HttpResponse pair. // That would allow to execute CONNECT method // behind the scene and return CONNECT HttpResponse // object in response to the original request that // contains the correct status line, headers & // response body. LOG.debug("CONNECT failed, fake the response for the original method"); // Pass the status, headers and response stream to the wrapped // method. // To ensure that the connection is not released more than once // this method is still responsible for releasing the connection. // This will happen when the response body is consumed, or when // the wrapped method closes the response connection in // releaseConnection(). if (method instanceof HttpMethodBase) { ((HttpMethodBase) method) .fakeResponse( this.connectMethod.getStatusLine(), this.connectMethod.getResponseHeaderGroup(), this.connectMethod.getResponseBodyAsStream()); method .getProxyAuthState() .setAuthScheme(this.connectMethod.getProxyAuthState().getAuthScheme()); this.connectMethod = null; } else { releaseConnection = true; LOG.warn("Unable to fake response on method as it is not derived from HttpMethodBase."); } }
private String getNotModified(String dataId, CacheData cacheData, HttpMethod httpMethod) { Header md5Header = httpMethod.getResponseHeader(Constants.CONTENT_MD5); if (null == md5Header) { throw new RuntimeException("RP_NO_CHANGE response not contain MD5"); } String md5 = md5Header.getValue(); if (!cacheData.getMd5().equals(md5)) { String lastMd5 = cacheData.getMd5(); cacheData.setMd5(Constants.NULL); cacheData.setLastModifiedHeader(Constants.NULL); throw new RuntimeException( "MD5 verify error,DataID:[" + dataId + "]MD5 last:[" + lastMd5 + "]MD5 current:[" + md5 + "]"); } cacheData.setMd5(md5); changeSpacingInterval(httpMethod); if (log.isInfoEnabled()) { log.info("DataId: " + dataId + ",not changed"); } return null; }
static { $SwitchMap$io$fabric$sdk$android$services$network$HttpMethod = new int[HttpMethod.values().length]; try { $SwitchMap$io$fabric$sdk$android$services$network$HttpMethod[HttpMethod.GET.ordinal()] = 1; } catch (NoSuchFieldError nosuchfielderror3) { } try { $SwitchMap$io$fabric$sdk$android$services$network$HttpMethod[HttpMethod.POST.ordinal()] = 2; } catch (NoSuchFieldError nosuchfielderror2) { } try { $SwitchMap$io$fabric$sdk$android$services$network$HttpMethod[HttpMethod.PUT.ordinal()] = 3; } catch (NoSuchFieldError nosuchfielderror1) { } try { $SwitchMap$io$fabric$sdk$android$services$network$HttpMethod[HttpMethod.DELETE.ordinal()] = 4; } catch (NoSuchFieldError nosuchfielderror) { return; } }
private void maybeCache() { Object obj = Internal.instance.internalCache(client); if (obj != null) { if (!CacheStrategy.isCacheable(userResponse, networkRequest)) { if (HttpMethod.invalidatesCache(networkRequest.method())) { try { ((InternalCache) (obj)).remove(networkRequest); return; } // Misplaced declaration of an exception variable catch (Object obj) { return; } } } else { storeRequest = ((InternalCache) (obj)).put(stripBody(userResponse)); return; } } }
public void sendRequest(MetaInfo meta) { System.out.println(Thread.currentThread().getId() + " start sendRequest"); URI uri = null; try { System.out.println(meta.getParams()); uri = new URI(meta.getUrl()); } catch (URISyntaxException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } String host = uri.getHost(); int port = 80; HttpRequest request = new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.valueOf(meta.getMethod()), uri.toASCIIString()); meta.buildHttpRequestHeader(request); ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); Channel channel = future.getChannel(); channel.getPipeline().addLast("handler", new DownloaderHandler()); GlobalVar.metaInfoVar.set(channel, meta); future.addListener(new ConnectOk(request)); channel.getCloseFuture().awaitUninterruptibly().addListener(new ConnectClose()); System.out.println(Thread.currentThread().getId() + " end sendRequest"); }
protected HttpContext read(HttpServletRequest request) throws IOException { String url = request.getPathInfo(); HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod()); HttpHeaders headers = this.headers(request); String content = this.content(request); return new HttpContext(url, httpMethod, headers, content); }
/* * (non-Javadoc) * @see org.jasig.portlet.weather.dao.IWeatherDao#find(java.lang.String) */ public Collection<Location> find(String location) { final String url = FIND_URL .replace("@KEY@", key) .replace("@QUERY@", QuietUrlCodec.encode(location, Constants.URL_ENCODING)); HttpMethod getMethod = new GetMethod(url); InputStream inputStream = null; try { // Execute the method. int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { final String statusText = getMethod.getStatusText(); throw new DataRetrievalFailureException( "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'"); } // Read the response body inputStream = getMethod.getResponseBodyAsStream(); List<Location> locations = deserializeSearchResults(inputStream); return locations; } catch (HttpException e) { throw new RuntimeException( "http protocol exception while getting data from weather service from: " + url, e); } catch (IOException e) { throw new RuntimeException( "IO exception while getting data from weather service from: " + url, e); } catch (JAXBException e) { throw new RuntimeException( "Parsing exception while getting data from weather service from: " + url, e); } finally { // try to close the inputstream IOUtils.closeQuietly(inputStream); // release the connection getMethod.releaseConnection(); } }
private String getSuccess( String dataId, String group, CacheData cacheData, HttpMethod httpMethod) { String configInfo = Constants.NULL; configInfo = getContent(httpMethod); if (null == configInfo) { throw new RuntimeException("RP_OK configInfo is null"); } Header md5Header = httpMethod.getResponseHeader(Constants.CONTENT_MD5); if (null == md5Header) { throw new RuntimeException("RP_OK not contain MD5, " + configInfo); } String md5 = md5Header.getValue(); if (!checkContent(configInfo, md5)) { throw new RuntimeException( "MD5 verify error,DataID:[" + dataId + "]ConfigInfo:[" + configInfo + "]MD5:[" + md5 + "]"); } Header lastModifiedHeader = httpMethod.getResponseHeader(Constants.LAST_MODIFIED); if (null == lastModifiedHeader) { throw new RuntimeException("RP_OK result not contain lastModifiedHeader"); } String lastModified = lastModifiedHeader.getValue(); cacheData.setMd5(md5); cacheData.setLastModifiedHeader(lastModified); changeSpacingInterval(httpMethod); String key = makeCacheKey(dataId, group); contentCache.put(key, configInfo); StringBuilder buf = new StringBuilder(); buf.append("dataId=").append(dataId); buf.append(" ,group=").append(group); buf.append(" ,content=").append(configInfo); dataLog.info(buf.toString()); return configInfo; }
private HttpUriRequest newHcRequest(HttpRequest request) throws IOException { URI uri = request.getUri().toJavaUri(); HttpUriRequest httpUriRequest = HttpMethod.valueOf(request.getMethod()).newMessage(uri); for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) { httpUriRequest.addHeader(entry.getKey(), StringUtils.join(entry.getValue(), ',')); } return httpUriRequest; }
protected Object getAndDeserialize(String url, TemperatureUnit unit) { HttpMethod getMethod = new GetMethod(url); InputStream inputStream = null; try { // Execute the method. int statusCode = httpClient.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { final String statusText = getMethod.getStatusText(); throw new DataRetrievalFailureException( "get of '" + url + "' failed with status '" + statusCode + "' due to '" + statusText + "'"); } // Read the response body inputStream = getMethod.getResponseBodyAsStream(); Weather weather = deserializeWeatherResult(inputStream, unit); return weather; } catch (HttpException e) { throw new RuntimeException( "http protocol exception while getting data from weather service from: " + url, e); } catch (IOException e) { throw new RuntimeException( "IO exception while getting data from weather service from: " + url, e); } catch (JAXBException e) { throw new RuntimeException( "Parsing exception while getting data from weather service from: " + url, e); } catch (ParseException e) { throw new RuntimeException( "Parsing exception while getting data from weather service from: " + url, e); } finally { // try to close the inputstream IOUtils.closeQuietly(inputStream); // release the connection getMethod.releaseConnection(); } }
Set<String> getUpdateDataIdsInBody(HttpMethod httpMethod) { Set<String> modifiedDataIdSet = new HashSet<String>(); try { String modifiedDataIdsString = httpMethod.getResponseBodyAsString(); return convertStringToSet(modifiedDataIdsString); } catch (Exception e) { } return modifiedDataIdSet; }
/** Returns the value of the {@code Access-Control-Allow-Methods} response header. */ public List<HttpMethod> getAccessControlAllowMethods() { List<HttpMethod> result = new ArrayList<HttpMethod>(); String value = getFirst(ACCESS_CONTROL_ALLOW_METHODS); if (value != null) { String[] tokens = value.split(",\\s*"); for (String token : tokens) { result.add(HttpMethod.valueOf(token)); } } return result; }
void changeSpacingInterval(HttpMethod httpMethod) { Header[] spacingIntervalHeaders = httpMethod.getResponseHeaders(Constants.SPACING_INTERVAL); if (spacingIntervalHeaders.length >= 1) { try { diamondConfigure.setPollingIntervalTime( Integer.parseInt(spacingIntervalHeaders[0].getValue())); } catch (RuntimeException e) { log.error("�����´μ��ʱ��ʧ��", e); } } }
private String generateSignature(Map<String, Object> params) { final String stringToSign = httpMethod.name() + "\n" + credentials.getApiHost().toLowerCase() + "\n" + path + "\n" + canonicalQueryString(params); return Utils.getHash(credentials.getSecretKey(), stringToSign); }