@Test public void testConnectionBasedAuthOnlyIfChallenged() throws Exception { HttpRequest request = new BasicHttpRequest("GET", "/"); HttpContext context = new BasicHttpContext(); AuthState authstate = new AuthState(); BasicScheme authscheme = new BasicScheme() { @Override public boolean isConnectionBased() { return true; } }; BasicHeader challenge = new BasicHeader(AUTH.WWW_AUTH, "BASIC realm=auth-realm"); authscheme.processChallenge(challenge); Credentials creds = new UsernamePasswordCredentials("user", "secret"); authstate.setState(AuthProtocolState.SUCCESS); authstate.update(authscheme, creds); context.setAttribute(ClientContext.TARGET_AUTH_STATE, authstate); HttpRequestInterceptor interceptor = new RequestTargetAuthentication(); interceptor.process(request, context); Header header = request.getFirstHeader(AUTH.WWW_AUTH_RESP); Assert.assertNull(header); }
public InputStream openGetStream(String url) throws ClientProtocolException, IOException { HttpGet request = new HttpGet(url); if (credentials != null) request.addHeader(BasicScheme.authenticate(credentials, "UTF-8", false)); HttpResponse response = execute(request); return response.getEntity().getContent(); }
@Test public void testNoTargetAuthForConnectRequests() throws Exception { HttpRequest request = new BasicHttpRequest("CONNECT", "www.somedomain.com"); HttpContext context = new BasicHttpContext(); BasicScheme authscheme = new BasicScheme(); Credentials creds = new UsernamePasswordCredentials("user", "secret"); BasicHeader challenge = new BasicHeader(AUTH.WWW_AUTH, "BASIC realm=auth-realm"); authscheme.processChallenge(challenge); AuthState authstate = new AuthState(); authstate.update(authscheme, creds); context.setAttribute(ClientContext.TARGET_AUTH_STATE, authstate); HttpRequestInterceptor interceptor = new RequestTargetAuthentication(); interceptor.process(request, context); Header header = request.getFirstHeader(AUTH.WWW_AUTH_RESP); Assert.assertNull(header); }
@Test public void testTargetAuth() throws Exception { HttpRequest request = new BasicHttpRequest("GET", "/"); HttpContext context = new BasicHttpContext(); BasicScheme authscheme = new BasicScheme(); Credentials creds = new UsernamePasswordCredentials("user", "secret"); BasicHeader challenge = new BasicHeader(AUTH.WWW_AUTH, "BASIC realm=auth-realm"); authscheme.processChallenge(challenge); AuthState authstate = new AuthState(); authstate.update(authscheme, creds); context.setAttribute(ClientContext.TARGET_AUTH_STATE, authstate); HttpRequestInterceptor interceptor = new RequestTargetAuthentication(); interceptor.process(request, context); Header header = request.getFirstHeader(AUTH.WWW_AUTH_RESP); Assert.assertNotNull(header); Assert.assertEquals("Basic dXNlcjpzZWNyZXQ=", header.getValue()); }
public InputStream openPostStream(String url, NameValuePair... postData) throws ClientProtocolException, IOException { HttpPost request = new HttpPost(url); if (credentials != null) request.addHeader(BasicScheme.authenticate(credentials, "UTF-8", false)); try { request.setEntity(new UrlEncodedFormEntity(Arrays.asList(postData))); } catch (UnsupportedEncodingException e) { } HttpResponse response = execute(request); return response.getEntity().getContent(); }
protected void createGetMethod(String url) { getMethod = new HttpGet(url); getMethod.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true); state.setAttribute(ClientContext.CREDS_PROVIDER, new WsdlCredentialsProvider()); if (SoapUI.getSettings().getBoolean(HttpSettings.AUTHENTICATE_PREEMPTIVELY)) { if (!StringUtils.isNullOrEmpty(getUsername()) && !StringUtils.isNullOrEmpty(getPassword())) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getUsername(), getPassword()); getMethod.addHeader(BasicScheme.authenticate(creds, "utf-8", false)); } } }
public static HttpGet createImageSearchRequest(String query) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("Sources", "'image'")); params.add(new BasicNameValuePair("Adult", "'Strict'")); params.add(new BasicNameValuePair("Query", "'" + query + "'")); params.add(new BasicNameValuePair("$format", "JSON")); String paramString = URLEncodedUtils.format(params, "UTF-8"); HttpGet request = new HttpGet(Constants.BING_SEARCH_URL + "?" + paramString); request.addHeader( BasicScheme.authenticate( new UsernamePasswordCredentials( Constants.BING_SEARCH_API_TOKEN, Constants.BING_SEARCH_API_TOKEN), "UTF-8", false)); return request; }
/** * Returns the HTTP POST request ready to be sent to the Stash build API for the given build and * change set. * * @param stashBuildNotificationEntity a entity containing the parameters for Stash * @param commitSha1 the SHA1 of the commit that was built * @return the HTTP POST request to the Stash build API */ private HttpPost createRequest( final HttpEntity stashBuildNotificationEntity, final String commitSha1) { String url = stashServerBaseUrl; String username = stashUserName; String pwd = Secret.toString(stashUserPassword); DescriptorImpl descriptor = getDescriptor(); if ("".equals(url) || url == null) url = descriptor.getStashRootUrl(); if ("".equals(username) || username == null) username = descriptor.getStashUser(); if ("".equals(pwd) || pwd == null) pwd = descriptor.getStashPassword().getPlainText(); HttpPost req = new HttpPost(url + "/rest/build-status/1.0/commits/" + commitSha1); req.addHeader( BasicScheme.authenticate(new UsernamePasswordCredentials(username, pwd), "UTF-8", false)); req.addHeader("Content-type", "application/json"); req.setEntity(stashBuildNotificationEntity); return req; }
public <T> Object doGetRequestResponse( String uri, Class<T> classType, String username, String password) { Object dataObject = null; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(uri); HttpResponse httpResponse = null; try { ((AbstractHttpClient) httpClient) .setCookieStore((org.apache.http.client.CookieStore) CookieStore.class.newInstance()); httpGet.addHeader( BasicScheme.authenticate( new UsernamePasswordCredentials(username, password), "UTF-8", false)); httpResponse = httpClient.execute(httpGet); if (isSuccess(httpResponse, HttpURLConnection.HTTP_OK)) { HttpEntity entity = httpResponse.getEntity(); if (entity != null) { String responseString = EntityUtils.toString(entity); dataObject = this.deSerialize(classType, responseString); } } } catch (InstantiationException e) { e.printStackTrace(); return e.getMessage(); } catch (IllegalAccessException e) { e.printStackTrace(); return e.getMessage(); } catch (ClientProtocolException e) { e.printStackTrace(); return e.getMessage(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } return dataObject; }
/* (non-Javadoc) * @see java.net.URLConnection#getInputStream() */ @Override public InputStream getInputStream() throws IOException { try { if (m_client == null) { connect(); } int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort(); String[] userInfo = m_url.getUserInfo() == null ? null : m_url.getUserInfo().split(":"); HttpGet request = new HttpGet( URIUtils.createURI( m_url.getProtocol(), m_url.getHost(), port, m_url.getPath(), m_url.getQuery(), null)); if (userInfo != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userInfo[0], userInfo[1]); request.addHeader(BasicScheme.authenticate(credentials, "UTF-8", false)); } HttpResponse response = m_client.execute(request); return response.getEntity().getContent(); } catch (Exception e) { throw new IOException( "Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(), e); } }
private Request newRequest(final URI uri) { final Header authenticateHeader = BasicScheme.authenticate(credentials, "UTF-8", false); return httpClient .newRequest(uri) .setHeader(authenticateHeader.getName(), authenticateHeader.getValue()); }
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { request.addHeader(BasicScheme.authenticate(credentials, "US-ASCII", false)); }
/* (non-Javadoc) * @see java.net.URLConnection#getInputStream() */ @Override public InputStream getInputStream() throws IOException { try { if (m_client == null) { connect(); } // Build URL int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort(); URIBuilder ub = new URIBuilder(); ub.setPort(port); ub.setScheme(m_url.getProtocol()); ub.setHost(m_url.getHost()); ub.setPath(m_url.getPath()); ub.setQuery(m_url.getQuery()); // Build Request HttpRequestBase request = null; if (m_request != null && m_request.getMethod().equalsIgnoreCase("post")) { final Content cnt = m_request.getContent(); HttpPost post = new HttpPost(ub.build()); ContentType contentType = ContentType.create(cnt.getType()); LOG.info("Processing POST request for %s", contentType); if (contentType .getMimeType() .equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) { FormFields fields = JaxbUtils.unmarshal(FormFields.class, cnt.getData()); post.setEntity(fields.getEntity()); } else { StringEntity entity = new StringEntity(cnt.getData(), contentType); post.setEntity(entity); } request = post; } else { request = new HttpGet(ub.build()); } if (m_request != null) { // Add Custom Headers for (Header header : m_request.getHeaders()) { request.addHeader(header.getName(), header.getValue()); } } // Add User Authentication String[] userInfo = m_url.getUserInfo() == null ? null : m_url.getUserInfo().split(":"); if (userInfo != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userInfo[0], userInfo[1]); request.addHeader(BasicScheme.authenticate(credentials, "UTF-8", false)); } // Get Response HttpResponse response = m_client.execute(request); return response.getEntity().getContent(); } catch (Exception e) { throw new IOException( "Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(), e); } }
@Override protected void download() { File destination = new File(request.getDestination()); final boolean fileExists = destination.exists(); if (request.isDeleteOnFailure() && fileExists) { Log.w(TAG, "File already exists"); if (request.getFeedfileType() != FeedImage.FEEDFILETYPE_FEEDIMAGE) { onFail(DownloadError.ERROR_FILE_EXISTS, null); return; } else { onSuccess(); return; } } HttpClient httpClient = AntennapodHttpClient.getHttpClient(); RandomAccessFile out = null; InputStream connection = null; try { HttpGet httpGet = new HttpGet(URIUtil.getURIFromRequestUrl(request.getSource())); // add authentication information String userInfo = httpGet.getURI().getUserInfo(); if (userInfo != null) { String[] parts = userInfo.split(":"); if (parts.length == 2) { httpGet.addHeader( BasicScheme.authenticate( new UsernamePasswordCredentials(parts[0], parts[1]), "UTF-8", false)); } } else if (!StringUtils.isEmpty(request.getUsername()) && request.getPassword() != null) { httpGet.addHeader( BasicScheme.authenticate( new UsernamePasswordCredentials(request.getUsername(), request.getPassword()), "UTF-8", false)); } // add range header if necessary if (fileExists) { request.setSoFar(destination.length()); httpGet.addHeader(new BasicHeader("Range", "bytes=" + request.getSoFar() + "-")); if (BuildConfig.DEBUG) Log.d(TAG, "Adding range header: " + request.getSoFar()); } HttpResponse response = httpClient.execute(httpGet); HttpEntity httpEntity = response.getEntity(); int responseCode = response.getStatusLine().getStatusCode(); Header contentEncodingHeader = response.getFirstHeader("Content-Encoding"); final boolean isGzip = contentEncodingHeader != null && contentEncodingHeader.getValue().equalsIgnoreCase("gzip"); if (BuildConfig.DEBUG) Log.d(TAG, "Response code is " + responseCode); if (responseCode / 100 != 2 || httpEntity == null) { final DownloadError error; final String details; if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { error = DownloadError.ERROR_UNAUTHORIZED; details = String.valueOf(responseCode); } else { error = DownloadError.ERROR_HTTP_DATA_ERROR; details = String.valueOf(responseCode); } onFail(error, details); return; } if (!StorageUtils.storageAvailable(PodcastApp.getInstance())) { onFail(DownloadError.ERROR_DEVICE_NOT_FOUND, null); return; } connection = new BufferedInputStream(AndroidHttpClient.getUngzippedContent(httpEntity)); Header[] contentRangeHeaders = (fileExists) ? response.getHeaders("Content-Range") : null; if (fileExists && responseCode == HttpStatus.SC_PARTIAL_CONTENT && contentRangeHeaders != null && contentRangeHeaders.length > 0) { String start = contentRangeHeaders[0] .getValue() .substring("bytes ".length(), contentRangeHeaders[0].getValue().indexOf("-")); request.setSoFar(Long.valueOf(start)); Log.d(TAG, "Starting download at position " + request.getSoFar()); out = new RandomAccessFile(destination, "rw"); out.seek(request.getSoFar()); } else { destination.delete(); destination.createNewFile(); out = new RandomAccessFile(destination, "rw"); } byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; request.setStatusMsg(R.string.download_running); if (BuildConfig.DEBUG) Log.d(TAG, "Getting size of download"); request.setSize(httpEntity.getContentLength() + request.getSoFar()); if (BuildConfig.DEBUG) Log.d(TAG, "Size is " + request.getSize()); if (request.getSize() < 0) { request.setSize(DownloadStatus.SIZE_UNKNOWN); } long freeSpace = StorageUtils.getFreeSpaceAvailable(); if (BuildConfig.DEBUG) Log.d(TAG, "Free space is " + freeSpace); if (request.getSize() != DownloadStatus.SIZE_UNKNOWN && request.getSize() > freeSpace) { onFail(DownloadError.ERROR_NOT_ENOUGH_SPACE, null); return; } if (BuildConfig.DEBUG) Log.d(TAG, "Starting download"); while (!cancelled && (count = connection.read(buffer)) != -1) { out.write(buffer, 0, count); request.setSoFar(request.getSoFar() + count); request.setProgressPercent( (int) (((double) request.getSoFar() / (double) request.getSize()) * 100)); } if (cancelled) { onCancelled(); } else { // check if size specified in the response header is the same as the size of the // written file. This check cannot be made if compression was used if (!isGzip && request.getSize() != DownloadStatus.SIZE_UNKNOWN && request.getSoFar() != request.getSize()) { onFail( DownloadError.ERROR_IO_ERROR, "Download completed but size: " + request.getSoFar() + " does not equal expected size " + request.getSize()); return; } onSuccess(); } } catch (IllegalArgumentException e) { e.printStackTrace(); onFail(DownloadError.ERROR_MALFORMED_URL, e.getMessage()); } catch (SocketTimeoutException e) { e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, e.getMessage()); } catch (UnknownHostException e) { e.printStackTrace(); onFail(DownloadError.ERROR_UNKNOWN_HOST, e.getMessage()); } catch (IOException e) { e.printStackTrace(); onFail(DownloadError.ERROR_IO_ERROR, e.getMessage()); } catch (NullPointerException e) { // might be thrown by connection.getInputStream() e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, request.getSource()); } finally { IOUtils.closeQuietly(out); AntennapodHttpClient.cleanup(); } }