List of usage examples for org.apache.http.client.methods HttpUriRequest getAllHeaders
Header[] getAllHeaders();
From source file:com.parse.ParseApacheHttpClientTest.java
@Test public void testGetApacheRequest() throws IOException { Map<String, String> headers = new HashMap<>(); String headerValue = "value"; headers.put("name", headerValue); String url = "http://www.parse.com/"; String content = "test"; String contentType = "application/json"; ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(url) .setMethod(ParseHttpRequest.Method.POST).setBody(new ParseByteArrayHttpBody(content, contentType)) .setHeaders(headers).build(); ParseApacheHttpClient parseClient = new ParseApacheHttpClient(10000, null); HttpUriRequest apacheRequest = parseClient.getRequest(parseRequest); // Verify method assertTrue(apacheRequest instanceof HttpPost); // Verify URL assertEquals(url, apacheRequest.getURI().toString()); // Verify Headers // We add gzip header to apacheRequest which does not contain in ParseRequest assertEquals(2, apacheRequest.getAllHeaders().length); assertEquals(1, apacheRequest.getHeaders("name").length); assertEquals("name", apacheRequest.getHeaders("name")[0].getName()); assertEquals(headerValue, apacheRequest.getHeaders("name")[0].getValue()); // Verify Body HttpPost apachePostRequest = (HttpPost) apacheRequest; assertEquals(4, apachePostRequest.getEntity().getContentLength()); assertEquals(contentType, apachePostRequest.getEntity().getContentType().getValue()); // Can not read parseRequest body to compare since it has been read during // creating apacheRequest assertArrayEquals(content.getBytes(), ParseIOUtils.toByteArray(apachePostRequest.getEntity().getContent())); }
From source file:org.apache.juneau.rest.client.RestCallLogger.java
@Override /* RestCallInterceptor */ public void onClose(RestCall restCall) throws RestCallException { try {//from www.j ava 2 s . c o m if (log.isLoggable(level)) { String output = restCall.getCapturedResponse(); StringBuilder sb = new StringBuilder(); HttpUriRequest req = restCall.getRequest(); HttpResponse res = restCall.getResponse(); if (req != null) { sb.append("\n=== HTTP Call (outgoing) ======================================================="); sb.append("\n=== REQUEST ===\n").append(req); sb.append("\n---request headers---"); for (Header h : req.getAllHeaders()) sb.append("\n\t").append(h); if (req instanceof HttpEntityEnclosingRequestBase) { sb.append("\n---request entity---"); HttpEntityEnclosingRequestBase req2 = (HttpEntityEnclosingRequestBase) req; HttpEntity e = req2.getEntity(); if (e == null) sb.append("\nEntity is null"); else { if (e.getContentType() != null) sb.append("\n").append(e.getContentType()); if (e.getContentEncoding() != null) sb.append("\n").append(e.getContentEncoding()); if (e.isRepeatable()) { try { sb.append("\n---request content---\n").append(EntityUtils.toString(e)); } catch (Exception ex) { throw new RuntimeException(ex); } } } } } if (res != null) { sb.append("\n=== RESPONSE ===\n").append(res.getStatusLine()); sb.append("\n---response headers---"); for (Header h : res.getAllHeaders()) sb.append("\n\t").append(h); sb.append("\n---response content---\n").append(output); sb.append("\n=== END ========================================================================"); } log.log(level, sb.toString()); } } catch (IOException e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); } }
From source file:io.wcm.caravan.io.http.impl.RequestUtilTest.java
@Test public void testBuildHttpRequest_Get() { RequestTemplate template = new RequestTemplate().method("get").append("/path").header("header1", "value1") .header("header2", "value2", "value3"); HttpUriRequest request = RequestUtil.buildHttpRequest("http://host", template.request()); assertEquals("http://host/path", request.getURI().toString()); assertEquals(HttpGet.METHOD_NAME, request.getMethod()); Map<String, Collection<String>> expected = ImmutableMap.<String, Collection<String>>of("header1", ImmutableList.of("value1"), "header2", ImmutableList.of("value2", "value3")); assertEquals(expected, RequestUtil.toHeadersMap(request.getAllHeaders())); }
From source file:com.clarionmedia.infinitum.web.rest.impl.CachingEnabledRestfulClient.java
private RestResponse executeRequest(HashableHttpRequest hashableHttpRequest) { if (mIsAuthenticated) mAuthStrategy.authenticate(hashableHttpRequest.unwrap()); if (mResponseCache.containsKey(hashableHttpRequest)) { RestResponse cachedResponse = mResponseCache.get(hashableHttpRequest); if (cachedResponse != null) return cachedResponse; }//from w w w . ja va 2 s . com HttpUriRequest httpRequest = hashableHttpRequest.unwrap(); mLogger.debug("Sending " + httpRequest.getMethod() + " request to " + httpRequest.getURI() + " with " + httpRequest.getAllHeaders().length + " headers"); HttpClient httpClient = new DefaultHttpClient(mHttpParams); try { HttpResponse response = httpClient.execute(httpRequest); RestResponse restResponse = new RestResponse(response); StatusLine statusLine = response.getStatusLine(); restResponse.setStatusCode(statusLine.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { restResponse.setResponseData(new byte[] {}); } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); entity.writeTo(out); out.close(); restResponse.setResponseData(out.toByteArray()); } long expiration = getResponseExpiration(restResponse); if (expiration > 0) mResponseCache.put(hashableHttpRequest, restResponse, expiration); return restResponse; } catch (ClientProtocolException e) { mLogger.error("Unable to send " + httpRequest.getMethod() + " request", e); return null; } catch (IOException e) { mLogger.error("Unable to read web service response", e); return null; } }
From source file:com.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java
private RestResponse executeRequest(HashableHttpRequest hashableHttpRequest) { if (mIsAuthenticated) mAuthStrategy.authenticate(hashableHttpRequest); if (mResponseCache.containsKey(hashableHttpRequest)) { RestResponse cachedResponse = mResponseCache.get(hashableHttpRequest); if (cachedResponse != null) return cachedResponse; }// w w w.j av a2 s . c om HttpUriRequest httpRequest = hashableHttpRequest.unwrap(); mLogger.debug("Sending " + httpRequest.getMethod() + " request to " + httpRequest.getURI() + " with " + httpRequest.getAllHeaders().length + " headers"); HttpClient httpClient = new DefaultHttpClient(mHttpParams); try { HttpResponse response = httpClient.execute(httpRequest); RestResponse restResponse = new RestResponse(response); StatusLine statusLine = response.getStatusLine(); restResponse.setStatusCode(statusLine.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { restResponse.setResponseData(new byte[] {}); } else { ByteArrayOutputStream out = new ByteArrayOutputStream(); entity.writeTo(out); out.close(); restResponse.setResponseData(out.toByteArray()); } long expiration = getResponseExpiration(restResponse); if (expiration > 0) mResponseCache.put(hashableHttpRequest, restResponse, expiration); return restResponse; } catch (ClientProtocolException e) { mLogger.error("Unable to send " + httpRequest.getMethod() + " request", e); return null; } catch (IOException e) { mLogger.error("Unable to read web service response", e); return null; } }
From source file:com.mutu.gpstracker.breadcrumbs.GetBreadcrumbsActivitiesTask.java
/** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token.//from w ww . j a v a2 s .c o m */ @Override protected Void doInBackground(Void... params) { mActivities = new LinkedList<Pair<Integer, String>>(); HttpEntity responseEntity = null; try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/activities.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Execute request: " + request.getURI()); for (Header header : request.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpClient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if (BreadcrumbsAdapter.DEBUG) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String activityName = null; Integer activityId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("activity".equals(xpp.getName()) && activityId != null && activityName != null) { mActivities.add(new Pair<Integer, String>(activityId, activityName)); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("id".equals(tagName)) { activityId = Integer.parseInt(xpp.getText()); } else if ("name".equals(tagName)) { activityName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_activity), e, "A problem while reading the XML data"); } finally { if (responseEntity != null) { try { //EntityUtils.consume(responseEntity); responseEntity.consumeContent(); } catch (IOException e) { Log.e(TAG, "Failed to close the content stream", e); } } } return null; }
From source file:com.snda.mymarket.providers.downloads.HurlStack.java
@Override public HttpResponse performRequest(HttpUriRequest request) throws IOException { String url = request.getURI().toString(); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); }/* ww w . ja v a 2 s . c o m*/ url = rewritten; } URL parsedUrl = new URL(url); client = openConnection(parsedUrl, request); for (Header headerName : request.getAllHeaders()) { client.addRequestProperty(headerName.getName(), headerName.getValue()); } client.setRequestMethod("GET"); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = client.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, client.getResponseCode(), client.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(client)); for (Entry<String, List<String>> header : client.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java
/** * ?.//ww w . j a v a2 s . co m * @param req ??Request * @param body ?? */ private void debugHttpRequest(final HttpUriRequest req, final String body) { log.debug(req.getURI()); if (log.isDebugEnabled()) { log.debug("?Request " + req.getMethod() + " " + req.getURI()); Header[] headers = req.getAllHeaders(); for (int i = 0; i < headers.length; i++) { log.debug("RequestHeader[" + headers[i].getName() + "] : " + headers[i].getValue()); } log.debug("RequestBody: " + body); } }
From source file:com.socialize.net.AsyncHttpRequestProcessor.java
@Override protected AsyncHttpResponse doInBackground(AsyncHttpRequest... params) { AsyncHttpRequest request = params[0]; AsyncHttpResponse response = new AsyncHttpResponse(); response.setRequest(request);//from w w w .ja v a 2s. c om try { HttpUriRequest httpRequest = request.getRequest(); if (!clientFactory.isDestroyed()) { if (logger != null && logger.isDebugEnabled()) { logger.debug( "Request: " + httpRequest.getMethod() + " " + httpRequest.getRequestLine().getUri()); StringBuilder builder = new StringBuilder(); Header[] allHeaders = httpRequest.getAllHeaders(); for (Header header : allHeaders) { builder.append(header.getName()); builder.append(":"); builder.append(header.getValue()); builder.append("\n"); } logger.debug("REQUEST \nurl:[" + httpRequest.getURI().toString() + "] \nheaders:\n" + builder.toString()); if (httpRequest instanceof HttpPost) { HttpPost post = (HttpPost) httpRequest; HttpEntity entity = post.getEntity(); if (!(entity instanceof MultipartEntity)) { String requestData = ioUtils.readSafe(entity.getContent()); logger.debug("REQUEST \ndata:[" + requestData + "]"); } } } HttpClient client = clientFactory.getClient(); HttpResponse httpResponse = client.execute(httpRequest); response.setResponse(httpResponse); if (logger != null && logger.isDebugEnabled()) { logger.debug("RESPONSE CODE: " + httpResponse.getStatusLine().getStatusCode()); } HttpEntity entity = null; try { entity = httpResponse.getEntity(); if (httpUtils.isHttpError(httpResponse)) { String msg = ioUtils.readSafe(entity.getContent()); throw new SocializeApiError(httpUtils, httpResponse.getStatusLine().getStatusCode(), msg); } else { String responseData = ioUtils.readSafe(entity.getContent()); if (logger != null && logger.isDebugEnabled()) { logger.debug("RESPONSE: " + responseData); } response.setResponseData(responseData); } } finally { closeEntity(entity); } } else { throw new SocializeException("Cannot execute http request. HttpClient factory was destroyed."); } } catch (Exception e) { response.setError(e); } return response; }
From source file:com.mutu.gpstracker.breadcrumbs.GetBreadcrumbsBundlesTask.java
/** * Retrieve the OAuth Request Token and present a browser to the user to * authorize the token./*from www. j av a 2s .com*/ */ @Override protected Void doInBackground(Void... params) { HttpEntity responseEntity = null; mBundleIds = new HashSet<Integer>(); mBundles = new LinkedList<Object[]>(); try { HttpUriRequest request = new HttpGet("http://api.gobreadcrumbs.com/v1/bundles.xml"); if (isCancelled()) { throw new IOException("Fail to execute request due to canceling"); } mConsumer.sign(request); if (BreadcrumbsAdapter.DEBUG) { Log.d(TAG, "Execute request: " + request.getURI()); for (Header header : request.getAllHeaders()) { Log.d(TAG, " with header: " + header.toString()); } } HttpResponse response = mHttpclient.execute(request); responseEntity = response.getEntity(); InputStream is = responseEntity.getContent(); InputStream stream = new BufferedInputStream(is, 8192); if (BreadcrumbsAdapter.DEBUG) { stream = XmlCreator.convertStreamToLoggedStream(TAG, stream); } XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(stream, "UTF-8"); String tagName = null; int eventType = xpp.getEventType(); String bundleName = null, bundleDescription = null; Integer bundleId = null; while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); } else if (eventType == XmlPullParser.END_TAG) { if ("bundle".equals(xpp.getName()) && bundleId != null) { mBundles.add(new Object[] { bundleId, bundleName, bundleDescription }); } tagName = null; } else if (eventType == XmlPullParser.TEXT) { if ("description".equals(tagName)) { bundleDescription = xpp.getText(); } else if ("id".equals(tagName)) { bundleId = Integer.parseInt(xpp.getText()); mBundleIds.add(bundleId); } else if ("name".equals(tagName)) { bundleName = xpp.getText(); } } eventType = xpp.next(); } } catch (OAuthMessageSignerException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "Failed to sign the request with authentication signature"); } catch (OAuthExpectationFailedException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The request did not authenticate"); } catch (OAuthCommunicationException e) { mService.removeAuthentication(); handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "The authentication communication failed"); } catch (IOException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } catch (XmlPullParserException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem while reading the XML data"); } catch (IllegalStateException e) { handleError(mContext.getString(R.string.taskerror_breadcrumbs_bundle), e, "A problem during communication"); } finally { if (responseEntity != null) { try { //EntityUtils.consume(responseEntity); responseEntity.consumeContent(); } catch (IOException e) { Log.w(TAG, "Failed closing inputstream"); } } } return null; }