List of usage examples for org.apache.http.client.methods HttpUriRequest setHeader
void setHeader(String str, String str2);
From source file:ch.entwine.weblounge.test.util.TestSiteUtils.java
/** * Test for the correct response when etag header is set. * // w ww .j ava2 s.c o m * @param request * the http request * @param eTagValue * the expected etag value * @param logger * used to log test output * @param params * the request parameters * @throws Exception * if processing the request fails */ public static void testETagHeader(HttpUriRequest request, String eTagValue, Logger logger, String[][] params) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); try { request.removeHeaders("If-Modified-Since"); request.setHeader("If-None-Match", eTagValue); logger.info("Sending 'If-None-Match' request to {}", request.getURI()); HttpResponse response = TestUtils.request(httpClient, request, params); assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode()); assertNull(response.getEntity()); } finally { httpClient.getConnectionManager().shutdown(); } httpClient = new DefaultHttpClient(); try { request.removeHeaders("If-Modified-Since"); request.setHeader("If-None-Match", "\"abcdefghijklmt\""); logger.info("Sending 'If-None-Match' request to {}", request.getURI()); HttpResponse response = TestUtils.request(httpClient, request, params); assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); assertNotNull(response.getEntity()); response.getEntity().consumeContent(); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:com.flurry.proguard.UploadProGuardMapping.java
private static HttpResponse executeHttpRequest(HttpUriRequest request, List<Header> requestHeaders) { for (Header header : requestHeaders) { request.setHeader(header.getName(), header.getValue()); }//from w ww . j ava 2s . c o m try { return HTTP_CLIENT.execute(request); } catch (IOException e) { failWithError("IO Exception during request: {}", request, e); return null; } }
From source file:com.neuron.trafikanten.HelperFunctions.java
public static StreamWithTime executeHttpRequest(Context context, HttpUriRequest request, boolean parseTime) throws IOException { //long perfSTART = System.currentTimeMillis(); /*/*ww w . j a va2 s . c o m*/ * Add gzip header */ request.setHeader("Accept-Encoding", "gzip"); request.setHeader("User-Agent", getUserAgent(context)); /* * Get the response, if we use gzip use the GZIPInputStream */ long responseTime = System.currentTimeMillis(); HttpResponse response = new DefaultHttpClient().execute(request); responseTime = (System.currentTimeMillis() - responseTime) / 2; InputStream content = response.getEntity().getContent(); /* * Get trafikanten time to calculate time difference */ long timeDifference = 0; if (parseTime) { try { final String header = response.getHeaders("Date")[0].getValue(); final long trafikantenTime = new Date(header).getTime(); //timeDifference = System.currentTimeMillis() - (System.currentTimeMillis() - timeDifference) - trafikantenTime; timeDifference = System.currentTimeMillis() - responseTime - trafikantenTime; Log.i(TAG, "Timedifference between local clock and trafikanten server : " + timeDifference + "ms (" + (timeDifference / 1000) + "s)"); } catch (Exception e) { e.printStackTrace(); // ignore this error, it's not critical. } } Header contentEncoding = response.getFirstHeader("Content-Encoding"); Header contentLength = response.getFirstHeader("Content-Length"); if (contentLength != null) { updateStatistics(context, Long.parseLong(contentLength.getValue())); } else { Log.e(TAG, "Contentlength is invalid!"); } if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { content = new GZIPInputStream(content); //Log.i(TAG,"Recieved compressed data - OK"); } else { Log.i(TAG, "Recieved UNCOMPRESSED data - Problem server side"); } //Log.i(TAG,"PERF : Sending web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms"); //return content; return new StreamWithTime(content, timeDifference); }
From source file:com.flurry.proguard.UploadMapping.java
private static CloseableHttpResponse executeHttpRequest(HttpUriRequest request, List<Header> requestHeaders) { for (Header header : requestHeaders) { request.setHeader(header.getName(), header.getValue()); }/*w w w . jav a2 s .c o m*/ try { return httpClient.execute(request); } catch (IOException e) { failWithError("IO Exception during request: {}", request, e); return null; } }
From source file:org.jwebsocket.sso.HTTPSupport.java
/** * * @param aURL// w ww. 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.amalto.workbench.utils.HttpClientUtil.java
public static String invokeCreateTDSCampaignService(String protocol, String host, String port, String contextPath, String username, String password, String modelName) throws XtentisException { try {// ww w . jav a 2s.co m String url = protocol + host + ":" + port + contextPath + "/services/rest/tds/setup?model=" + modelName; //$NON-NLS-1$ //$NON-NLS-2$ DefaultHttpClient httpClient = wrapAuthClient(url, username, password); HttpUriRequest request = new HttpPut(url); request.setHeader("Accept", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$ addStudioToken(request, username); HttpContext preemptiveContext = getPreemptiveContext(url); authenticate(username, password, request, preemptiveContext); String errMessage = Messages.Util_21 + "%s" + Messages.Util_22 + "%s"; //$NON-NLS-1$//$NON-NLS-2$ String content = getResponseContent(httpClient, request, null, errMessage, String.class, true); if (content == null) { content = ""; //$NON-NLS-1$ } return content; } catch (SecurityException e) { log.error(e.getMessage(), e); } return null; }
From source file:ch.entwine.weblounge.test.util.TestSiteUtils.java
/** * Test for the correct response when modified since header is set. * //w w w. j a va 2 s. c o m * @param request * the http request * @param date * the expected modification date * @param logger * used to log test output * @param params * the request parameters * @throws Exception * if processing the request fails */ public static void testModifiedHeader(HttpUriRequest request, Date modificationDate, Logger logger, String[][] params) throws Exception { DefaultHttpClient httpClient = new DefaultHttpClient(); Date before = new Date(modificationDate.getTime() - Times.MS_PER_DAY); Date after = new Date(modificationDate.getTime() + Times.MS_PER_DAY); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); try { request.removeHeaders("If-None-Match"); request.setHeader("If-Modified-Since", format.format(after)); logger.info("Sending 'If-Modified-Since' request to {}", request.getURI()); HttpResponse response = TestUtils.request(httpClient, request, params); assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatusLine().getStatusCode()); assertNull(response.getEntity()); } finally { httpClient.getConnectionManager().shutdown(); } httpClient = new DefaultHttpClient(); try { request.removeHeaders("If-None-Match"); request.setHeader("If-Modified-Since", format.format(before)); logger.info("Sending 'If-Modified-Since' request to {}", request.getURI()); HttpResponse response = TestUtils.request(httpClient, request, params); assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); assertNotNull(response.getEntity()); response.getEntity().consumeContent(); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:org.deviceconnect.message.intent.util.IntentAuthProcessor.java
/** * ????. Device Connect Manager??????????? * Device Connect Manager??Intent??<br/> * ?????Intent????????UI?????<strong>????</strong><br/> * ??? AndroidManifest.xml??// w w w . j a v a 2s . co m * {@link org.deviceconnect.message.intent.impl.io.IntentResponseReceiver} * ????? * * @param context * @param componentName Device Connect Manager???? * @param packageName Authorization Create Client API?package? * @param appName Authorization Create Access Token * API?applicationName? * @param scopes Authorization Create Access Token API?scope? * @param callback ?????? */ public static void authorize(final Context context, final ComponentName componentName, final String packageName, final String appName, final String[] scopes, final AuthorizationHandler callback) { if (callback == null) { throw new IllegalArgumentException("Callback is null."); } else if (scopes == null || scopes.length == 0) { throw new IllegalArgumentException("No scopes."); } else if (componentName == null) { throw new IllegalArgumentException("componentName is null."); } else if (packageName == null) { throw new IllegalArgumentException("Package name is null."); } else if (appName == null) { throw new IllegalArgumentException("App name is null."); } if (Thread.currentThread().equals(context.getMainLooper().getThread())) { throw new IllegalStateException("DON'T CALL this method in UI thread."); } URIBuilder builder = new URIBuilder(); // ??ComponentName????????????????????? builder.setHost("localhost"); builder.setPort(0); builder.setScheme("http"); builder.setProfile(AuthorizationProfileConstants.PROFILE_NAME); builder.setAttribute(AuthorizationProfileConstants.ATTRIBUTE_CREATE_CLIENT); builder.addParameter(AuthorizationProfileConstants.PARAM_PACKAGE, packageName); HttpUriRequest request = null; try { request = new HttpGet(builder.build()); } catch (URISyntaxException e1) { throw new IllegalArgumentException("Invalid Param. Check parameters."); } // DefaultIntentClient?????Host????????????????? request.setHeader(HttpHeaders.HOST, componentName.flattenToShortString()); ErrorCode error = null; HttpParams params = new BasicHttpParams(); IntentConnectionParams.setContext(params, context); IntentConnectionParams.setComponent(params, componentName); DefaultIntentClient client = new DefaultIntentClient(params); do { try { JSONObject json = execute(client, request); error = checkResponse(json); if (error != null) { break; } String clientId = json.getString(AuthorizationProfileConstants.PARAM_CLIENT_ID); String clientSecret = json.getString(AuthorizationProfileConstants.PARAM_CLIENT_SECRET); String signature = AuthSignature.generateSignature(clientId, AuthorizationProfileConstants.GrantType.AUTHORIZATION_CODE.getValue(), null, scopes, clientSecret); // ??? builder.setAttribute(AuthorizationProfileConstants.ATTRIBUTE_REQUEST_ACCESS_TOKEN); builder.addParameter(AuthorizationProfileConstants.PARAM_CLIENT_ID, clientId); builder.addParameter(AuthorizationProfileConstants.PARAM_SCOPE, combineStr(scopes)); builder.addParameter(AuthorizationProfileConstants.PARAM_GRANT_TYPE, AuthorizationProfileConstants.GrantType.AUTHORIZATION_CODE.getValue()); builder.addParameter(AuthorizationProfileConstants.PARAM_SIGNATURE, signature); builder.addParameter(AuthorizationProfileConstants.PARAM_APPLICATION_NAME, appName); try { request = new HttpGet(builder.build()); } catch (URISyntaxException e1) { error = ErrorCode.UNKNOWN; break; } // client?????????? client.getConnectionManager().shutdown(); client = new DefaultIntentClient(params); json = execute(client, request); error = checkResponse(json); if (error != null) { break; } String accessToken = json.getString(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN); callback.onAuthorized(clientId, clientSecret, accessToken); } catch (Exception e) { error = ErrorCode.UNKNOWN; e.printStackTrace(); break; } } while (false); client.getConnectionManager().shutdown(); if (error != null) { callback.onAuthFailed(error); } }
From source file:emea.summit.architects.HackathlonAPIResource.java
private static String getRequest(String url, String contentType) throws Exception { HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.build(); HttpUriRequest get = new HttpGet(url); get.setHeader("Content-Type", contentType); HttpResponse response = client.execute(get); StatusLine status = response.getStatusLine(); String content = EntityUtils.toString(response.getEntity()); //JSONObject json = new JSONObject(content); return content; }
From source file:emea.summit.architects.HackathlonAPIResource.java
private static String putRequest(String url, String contentType) throws Exception { HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.build(); HttpUriRequest put = new HttpPut(url); put.setHeader("Content-Type", contentType); HttpResponse response = client.execute(put); StatusLine status = response.getStatusLine(); String content = EntityUtils.toString(response.getEntity()); //JSONObject json = new JSONObject(content); return content; }