List of usage examples for org.apache.http.client.methods HttpRequestBase setURI
public void setURI(final URI uri)
From source file:com.trellmor.berrymotes.sync.SubredditEmoteDownloader.java
private List<EmoteImage> downloadEmoteList() throws URISyntaxException, IOException, InterruptedException { checkInterrupted();/*from w w w . ja va 2 s. c o m*/ Log.debug("Downloading " + mSubreddit + EMOTES); HttpRequestBase request = new HttpGet(); request.setURI(new URI(EmoteDownloader.HOST + mSubreddit + EMOTES)); request.setHeader("If-Modified-Since", DateUtils.formatDate(mLastModified)); mEmoteDownloader.checkCanDownload(); HttpResponse response = mEmoteDownloader.getHttpClient().execute(request); switch (response.getStatusLine().getStatusCode()) { case 200: Log.debug(mSubreddit + EMOTES + " loaded"); // Download ok Header[] lastModified = response.getHeaders("last-modified"); if (lastModified.length > 0) { try { mLastModified = DateUtils.parseDate(lastModified[0].getValue()); } catch (DateParseException e) { Log.error("Error parsing last-modified header", e); } } HttpEntity entity = response.getEntity(); if (entity != null) { checkInterrupted(); File tmpFile = File.createTempFile(mSubreddit, null, mContext.getCacheDir()); try { InputStream is = entity.getContent(); try { mEmoteDownloader.checkStorageAvailable(); StreamUtils.saveStreamToFile(is, tmpFile); } finally { StreamUtils.closeStream(is); } FileInputStream fis = null; BufferedInputStream bis = null; GZIPInputStream zis = null; Reader isr = null; JsonReader jsonReader = null; checkInterrupted(); try { fis = new FileInputStream(tmpFile); bis = new BufferedInputStream(fis); zis = new GZIPInputStream(bis); isr = new InputStreamReader(zis, "UTF-8"); jsonReader = new JsonReader(isr); jsonReader.beginArray(); Gson gson = new Gson(); ArrayList<EmoteImage> emotes = new ArrayList<EmoteImage>(); while (jsonReader.hasNext()) { EmoteImage emote = gson.fromJson(jsonReader, EmoteImage.class); emotes.add(emote); } jsonReader.endArray(); Log.info("Loaded " + mSubreddit + EMOTES + ", size: " + Integer.toString(emotes.size())); return emotes; } finally { StreamUtils.closeStream(jsonReader); StreamUtils.closeStream(isr); StreamUtils.closeStream(zis); StreamUtils.closeStream(bis); StreamUtils.closeStream(fis); } } finally { tmpFile.delete(); } } break; case 304: Log.info(mSubreddit + EMOTES + " already up to date (HTTP 304)"); break; case 403: case 404: Log.info(mSubreddit + " missing on server, removing emotes"); mEmoteDownloader.deleteSubreddit(mSubreddit, mContentResolver); break; default: throw new IOException("Unexpected HTTP response: " + response.getStatusLine().getReasonPhrase()); } return null; }
From source file:org.forgerock.openig.http.HttpClient.java
/** * Submits the request to the remote server. Creates and populates the * response from that provided by the remote server. * * @param request The HTTP request to send. * @return The HTTP response.//from w w w.ja va 2 s .c om * @throws IOException If an IO error occurred while performing the request. */ public Response execute(final Request request) throws IOException { final HttpRequestBase clientRequest = request.entity != null ? new EntityRequest(request) : new NonEntityRequest(request); clientRequest.setURI(request.uri); // connection headers to suppress final CaseInsensitiveSet suppressConnection = new CaseInsensitiveSet(); // parse request connection headers to be suppressed in request suppressConnection.addAll(new ConnectionHeader(request).getTokens()); // request headers for (final String name : request.headers.keySet()) { if (!SUPPRESS_REQUEST_HEADERS.contains(name) && !suppressConnection.contains(name)) { for (final String value : request.headers.get(name)) { clientRequest.addHeader(name, value); } } } // send request final HttpResponse clientResponse = httpClient.execute(clientRequest); final Response response = new Response(); // response entity final HttpEntity clientResponseEntity = clientResponse.getEntity(); if (clientResponseEntity != null) { response.entity = new BranchingStreamWrapper(clientResponseEntity.getContent(), storage); } // response status line final StatusLine statusLine = clientResponse.getStatusLine(); response.version = statusLine.getProtocolVersion().toString(); response.status = statusLine.getStatusCode(); response.reason = statusLine.getReasonPhrase(); // parse response connection headers to be suppressed in response suppressConnection.clear(); suppressConnection.addAll(new ConnectionHeader(response).getTokens()); // response headers for (final HeaderIterator i = clientResponse.headerIterator(); i.hasNext();) { final Header header = i.nextHeader(); final String name = header.getName(); if (!SUPPRESS_RESPONSE_HEADERS.contains(name) && !suppressConnection.contains(name)) { response.headers.add(name, header.getValue()); } } // TODO: decide if need to try-finally to call httpRequest.abort? return response; }
From source file:de.m0ep.canvas.CanvasLmsRequest.java
private HttpResponse executeUnparsed() throws CanvasLmsException { HttpRequestBase request = null; try {//from w w w .j a v a 2s.c o m request = getMethodType().newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new CanvasLmsException("Failed to create requeset method object.", e); } try { request.setURI(new URI(getUri())); } catch (URISyntaxException e) { throw new CanvasLmsException("Invalid uri", e); } if (null != getOauthToken()) { request.addHeader("Authorization", "Bearer " + getOauthToken()); } if (null != getContent()) { // Set the content, if the request method can handle it if (request instanceof HttpEntityEnclosingRequest) { ((HttpEntityEnclosingRequest) request).setEntity(getContent()); } } LOG.info("Send '{}' request to '{}'.", getMethodType().getSimpleName(), getUri(), getResponseType().getSimpleName()); try { return getClient().getHttpClient().execute(request); } catch (IOException e) { throw new NetworkException("Failed to execute " + getMethodType().getSimpleName() + " request.", e); } }
From source file:com.payu.sdk.helper.HttpClientHelper.java
/** * Creates a http request with the given request * * @param request//w w w .ja va2s. c om * The original request * @param requestMethod * The request method to be sent to the server * @return The created http request * @throws URISyntaxException * @throws UnsupportedEncodingException * @throws PayUException * @throws ConnectionException */ private static HttpRequestBase createHttpRequest(Request request, RequestMethod requestMethod) throws URISyntaxException, UnsupportedEncodingException, PayUException, ConnectionException { String url = request.getRequestUrl(requestMethod); URI postUrl = new URI(url); HttpRequestBase httpMethod; LoggerUtil.debug("sending request..."); String xml = Constants.EMPTY_STRING; switch (requestMethod) { case POST: httpMethod = new HttpPost(); break; case GET: httpMethod = new HttpGet(); break; case DELETE: httpMethod = new HttpDelete(); break; case PUT: httpMethod = new HttpPut(); break; default: throw new ConnectionException("Invalid connection method"); } httpMethod.addHeader("Content-Type", MediaType.XML.getCode() + "; charset=utf-8"); Language lng = request.getLanguage() != null ? request.getLanguage() : PayU.language; httpMethod.setHeader("Accept-Language", lng.name()); // Sets the method entity if (httpMethod instanceof HttpEntityEnclosingRequestBase) { xml = request.toXml(); ((HttpEntityEnclosingRequestBase) httpMethod) .setEntity(new StringEntity(xml, Constants.DEFAULT_ENCODING)); LoggerUtil.debug("Message to send:\n {0}", xml); } httpMethod.setURI(postUrl); addRequestHeaders(request, httpMethod); LoggerUtil.debug("URL to send:\n {0}", url); return httpMethod; }
From source file:com.seleritycorp.common.base.http.client.HttpRequest.java
private org.apache.http.HttpResponse getHttpResponse() throws HttpException { final HttpRequestBase request; switch (method) { case HttpGet.METHOD_NAME: request = new HttpGet(); break;//ww w . ja v a 2 s . com case HttpPost.METHOD_NAME: request = new HttpPost(); break; default: throw new HttpException("Unknown HTTP method '" + method + "'"); } try { request.setURI(URI.create(uri)); } catch (IllegalArgumentException e) { throw new HttpException("Failed to create URI '" + uri + "'", e); } if (userAgent != null) { request.setHeader(HTTP.USER_AGENT, userAgent); } if (readTimeoutMillis >= 0) { request.setConfig(RequestConfig.custom().setSocketTimeout(readTimeoutMillis) .setConnectTimeout(readTimeoutMillis).setConnectionRequestTimeout(readTimeoutMillis).build()); } if (!data.isEmpty()) { if (request instanceof HttpEntityEnclosingRequestBase) { final HttpEntity entity; ContentType localContentType = contentType; if (localContentType == null) { localContentType = ContentType.create("text/plain", StandardCharsets.UTF_8); } entity = new StringEntity(data, localContentType); HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request; entityRequest.setEntity(entity); } else { throw new HttpException( "Request " + request.getMethod() + " does not allow to send data " + "with the request"); } } final HttpClient httpClient; if (uri.startsWith("file://")) { httpClient = this.fileHttpClient; } else { httpClient = this.netHttpClient; } final org.apache.http.HttpResponse response; try { response = httpClient.execute(request); } catch (IOException e) { throw new HttpException("Failed to execute request to '" + uri + "'", e); } return response; }
From source file:com.mirth.connect.client.core.ServerConnection.java
private HttpRequestBase setupRequestBase(ClientRequest request, ExecuteType executeType) { HttpRequestBase requestBase = getRequestBase(executeType, request.getMethod()); requestBase.setURI(request.getUri()); for (Entry<String, List<String>> entry : request.getStringHeaders().entrySet()) { for (String value : entry.getValue()) { requestBase.addHeader(entry.getKey(), value); }//from w w w . j av a 2s .co m } if (request.hasEntity() && requestBase instanceof HttpEntityEnclosingRequestBase) { final HttpEntityEnclosingRequestBase entityRequestBase = (HttpEntityEnclosingRequestBase) requestBase; entityRequestBase.setEntity(new ClientRequestEntity(request)); } return requestBase; }
From source file:mobi.jenkinsci.ci.client.JenkinsHttpClient.java
private void ensurePreemptiveAuthRequest(final HttpRequestBase req) { final String username = config.getUsername(); final String password = config.getPassword(); final URI reqUri = req.getURI(); final String reqUriString = reqUri.toString(); if (reqUriString.indexOf(username) < 0) { try {/* www .ja va 2 s . c o m*/ final String newUriString = reqUriString.replaceAll("://", "://" + URLEncoder.encode(username, "UTF-8") + ":" + URLEncoder.encode(password, "UTF-8") + "@"); req.setURI(new URI(newUriString)); } catch (final Exception e) { LOG.error("Cannot insert user into URI " + reqUriString, e); return; } } }
From source file:com.kolich.havalo.client.service.HavaloClient.java
public Either<HttpFailure, ObjectList> listObjects(final String... path) { // The listing of objects is only successful when the // resulting status code is a 200 OK. Any other status // code on the response is failure. return new HavaloGsonClosure<ObjectList>(client_, gson_.create(), ObjectList.class, SC_OK) { @Override//from ww w. j a v a 2 s . c o m public void before(final HttpRequestBase request) throws Exception { final URIBuilder builder = new URIBuilder(request.getURI()); if (path != null && path.length > 0) { builder.addParameter(API_PARAM_STARTSWITH, varargsToPrefixString(path)); } request.setURI(builder.build()); super.before(request); } }.get(API_ACTION_REPOSITORY); }
From source file:com.github.grantjforrester.bdd.rest.httpclient.HttpClientRequest.java
HttpRequestBase getRequestImpl(URI baseUri) { HttpRequestBase request = null; switch (method) { case HEAD://from w ww.jav a 2s.co m request = new HttpHead(); break; case OPTIONS: request = new HttpOptions(); break; case GET: request = new HttpGet(); break; case POST: request = new HttpPost(); break; case PUT: request = new HttpPut(); break; case DELETE: request = new HttpDelete(); break; case PATCH: request = new HttpPatch(); } request.setURI(baseUri.resolve(uri)); request.setHeaders(headers.toArray(new Header[headers.size()])); if (content != null) { ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(content)); } return request; }
From source file:com.mgmtp.perfload.core.client.web.request.HttpRequestHandler.java
/** * Creates the request object.//from w ww .j av a 2s. co m * * @param type * the type of the HTTP request (GET, TRACE, DELETE, OPTIONS, HEAD, POST, PUT) * @param uri * the uri * @param parameters * the request parameters * @param body * the request body * @return the request */ protected HttpRequestBase createRequest(final String type, final URI uri, final List<NameValuePair> parameters, final Body body) throws Exception { HttpRequestBase request = HttpMethod.valueOf(type).create(uri); if (!(request instanceof HttpEntityEnclosingRequest)) { // GET, TRACE, DELETE, OPTIONS, HEAD if (!parameters.isEmpty()) { String query = URLEncodedUtils.format(parameters, "UTF-8"); URI requestURI = new URI( uri.getRawQuery() == null ? uri.toString() + '?' + query : uri.toString() + '&' + query); request.setURI(requestURI); } } else { // POST, PUT final HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; if (body != null) { // this only sets the content, header come from the request flow entityRequest.setEntity(new ByteArrayEntity(body.getContent())); } else { checkState(request instanceof HttpPost, "Invalid request: " + request.getMethod() + ". Cannot add post parameters to this kind of request. Please check the request flow."); entityRequest.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); } } return request; }