List of usage examples for java.net HttpURLConnection HTTP_MOVED_TEMP
int HTTP_MOVED_TEMP
To view the source code for java.net HttpURLConnection HTTP_MOVED_TEMP.
Click Source Link
From source file:ca.osmcanada.osvuploadr.JPMain.java
private String sendForm(String target_url, Map<String, String> arguments, String method, List<Cookie> cookielist) { try {//w w w .j ava 2 s . c o m URL url = new URL(target_url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); //HttpURLConnection http = (HttpURLConnection)con; con.setRequestMethod(method); // PUT is another valid option con.setDoOutput(true); con.setInstanceFollowRedirects(false); String cookiestr = ""; if (cookielist != null) { if (cookielist.size() > 0) { for (Cookie cookie : cookielist) { if (!cookiestr.equals("")) { cookiestr += ";" + cookie.getName() + "=" + cookie.getValue(); } else { cookiestr += cookie.getName() + "=" + cookie.getValue(); } } con.setRequestProperty("Cookie", cookiestr); } } con.setReadTimeout(5000); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; con.setFixedLengthStreamingMode(length); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); con.setRequestProperty("Accept-Language", "en-us;"); con.connect(); try (OutputStream os = con.getOutputStream()) { os.write(out); os.close(); } boolean redirect = false; int status = con.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { String newURL = con.getHeaderField("Location"); String cookies = con.getHeaderField("Set-Cookie"); if (cookies == null) { cookies = cookiestr; } con = (HttpURLConnection) new URL(newURL).openConnection(); con.setRequestProperty("Cookie", cookies); } InputStream is = con.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray(), Charset.forName("UTF-8")); con.disconnect(); return data; } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } return ""; }
From source file:net.dahanne.gallery3.client.business.G3Client.java
private HttpEntity requestToResponseEntity(String appendToGalleryUrl, List<NameValuePair> nameValuePairs, String requestMethod, File file) throws UnsupportedEncodingException, IOException, ClientProtocolException, G3GalleryException { HttpClient defaultHttpClient = new DefaultHttpClient(); HttpRequestBase httpMethod;/*from ww w . j av a 2 s .co m*/ //are we using rewritten urls ? if (this.isUsingRewrittenUrls && appendToGalleryUrl.contains(INDEX_PHP_REST)) { appendToGalleryUrl = StringUtils.remove(appendToGalleryUrl, "index.php"); } logger.debug("requestToResponseEntity , url requested : {}", galleryItemUrl + appendToGalleryUrl); if (POST.equals(requestMethod)) { httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); if (file != null) { MultipartEntity multipartEntity = new MultipartEntity(); String string = nameValuePairs.toString(); // dirty fix to remove the enclosing entity{} String substring = string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1); StringBody contentBody = new StringBody(substring, Charset.forName("UTF-8")); multipartEntity.addPart("entity", contentBody); FileBody fileBody = new FileBody(file); multipartEntity.addPart("file", fileBody); ((HttpPost) httpMethod).setEntity(multipartEntity); } else { ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } } else if (PUT.equals(requestMethod)) { httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } else if (DELETE.equals(requestMethod)) { httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl); httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); //this is to avoid the HTTP 414 (length too long) error //it should only happen when getting items, index.php/rest/items?urls= // } else if(appendToGalleryUrl.length()>2000) { // String resource = appendToGalleryUrl.substring(0,appendToGalleryUrl.indexOf("?")); // String variable = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("?")+1,appendToGalleryUrl.indexOf("=")); // String value = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("=")+1); // httpMethod = new HttpPost(galleryItemUrl + resource); // httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod); // nameValuePairs.add(new BasicNameValuePair(variable, value)); // ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity( // nameValuePairs)); } else { httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl); } if (existingApiKey != null) { httpMethod.setHeader(X_GALLERY_REQUEST_KEY, existingApiKey); } //adding the userAgent to the request httpMethod.setHeader(USER_AGENT, userAgent); HttpResponse response = null; String[] patternsArray = new String[3]; patternsArray[0] = "EEE, dd MMM-yyyy-HH:mm:ss z"; patternsArray[1] = "EEE, dd MMM yyyy HH:mm:ss z"; patternsArray[2] = "EEE, dd-MMM-yyyy HH:mm:ss z"; try { // be extremely careful here, android httpclient needs it to be // an // array of string, not an arraylist defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsArray); response = defaultHttpClient.execute(httpMethod); } catch (ClassCastException e) { List<String> patternsList = Arrays.asList(patternsArray); defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsList); response = defaultHttpClient.execute(httpMethod); } int responseStatusCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = null; if (response.getEntity() != null) { responseEntity = response.getEntity(); } switch (responseStatusCode) { case HttpURLConnection.HTTP_CREATED: break; case HttpURLConnection.HTTP_OK: break; case HttpURLConnection.HTTP_MOVED_TEMP: //the gallery is using rewritten urls, let's remember it and re hit the server this.isUsingRewrittenUrls = true; responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file); break; case HttpURLConnection.HTTP_BAD_REQUEST: throw new G3BadRequestException(); case HttpURLConnection.HTTP_FORBIDDEN: //for some reasons, the gallery may respond with 403 when trying to log in with the wrong url if (appendToGalleryUrl.contains(INDEX_PHP_REST)) { this.isUsingRewrittenUrls = true; responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file); break; } throw new G3ForbiddenException(); case HttpURLConnection.HTTP_NOT_FOUND: throw new G3ItemNotFoundException(); default: throw new G3GalleryException("HTTP code " + responseStatusCode); } return responseEntity; }
From source file:org.jboss.as.test.integration.web.formauth.FormAuthUnitTestCase.java
/** * Test that a post from an unsecured form to a secured servlet does not * loose its data during the redirct to the form login. *//* ww w . ja v a2 s . c om*/ @Test @OperateOnDeployment("form-auth.war") public void testPostDataFormAuth() throws Exception { log.info("+++ testPostDataFormAuth"); URL url = new URL(baseURLNoAuth + "unsecure_form.html"); HttpGet httpget = new HttpGet(url.toURI()); log.info("Executing request " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); int statusCode = response.getStatusLine().getStatusCode(); Header[] errorHeaders = response.getHeaders("X-NoJException"); assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK); assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0); EntityUtils.consume(response.getEntity()); // Submit the form to /restricted/SecuredPostServlet HttpPost restrictedPost = new HttpPost(baseURLNoAuth + "restricted/SecuredPostServlet"); List<NameValuePair> restrictedParams = new ArrayList<NameValuePair>(); restrictedParams.add(new BasicNameValuePair("checkParam", "123456")); restrictedPost.setEntity(new UrlEncodedFormEntity(restrictedParams, "UTF-8")); log.info("Executing request " + restrictedPost.getRequestLine()); HttpResponse restrictedResponse = httpclient.execute(restrictedPost); statusCode = restrictedResponse.getStatusLine().getStatusCode(); errorHeaders = restrictedResponse.getHeaders("X-NoJException"); assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK); assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0); HttpEntity entity = restrictedResponse.getEntity(); if ((entity != null) && (entity.getContentLength() > 0)) { String body = EntityUtils.toString(entity); assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0); } else { fail("Empty body in response"); } String sessionID = null; for (Cookie k : httpclient.getCookieStore().getCookies()) { if (k.getName().equalsIgnoreCase("JSESSIONID")) sessionID = k.getValue(); } log.info("Saw JSESSIONID=" + sessionID); // Submit the login form HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check"); formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("j_username", "user1")); formparams.add(new BasicNameValuePair("j_password", "password1")); formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8")); log.info("Executing request " + formPost.getRequestLine()); HttpResponse postResponse = httpclient.execute(formPost); statusCode = postResponse.getStatusLine().getStatusCode(); errorHeaders = postResponse.getHeaders("X-NoJException"); assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode, statusCode == HttpURLConnection.HTTP_MOVED_TEMP); assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0); EntityUtils.consume(postResponse.getEntity()); // Follow the redirect to the SecureServlet Header location = postResponse.getFirstHeader("Location"); URL indexURI = new URL(location.getValue()); HttpGet war1Index = new HttpGet(url.toURI()); log.info("Executing request " + war1Index.getRequestLine()); HttpResponse war1Response = httpclient.execute(war1Index); statusCode = war1Response.getStatusLine().getStatusCode(); errorHeaders = war1Response.getHeaders("X-NoJException"); assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK); assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0); HttpEntity war1Entity = war1Response.getEntity(); if ((war1Entity != null) && (entity.getContentLength() > 0)) { String body = EntityUtils.toString(war1Entity); if (body.indexOf("j_security_check") > 0) fail("Get of " + indexURI + " redirected to login page"); } else { fail("Empty body in response"); } }
From source file:be.cytomine.client.HttpClient.java
public static BufferedImage readBufferedImageFromRETRIEVAL(String url, String publicKey, String privateKey, String host) throws IOException { log.debug("readBufferedImageFromURL:" + url); URL URL = new URL(url); HttpHost targetHost = new HttpHost(URL.getHost(), URL.getPort()); log.debug("targetHost:" + targetHost); DefaultHttpClient client = new DefaultHttpClient(); log.debug("client:" + client); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); log.debug("localcontext:" + localcontext); Header[] headers = authorizeFromRETRIEVAL("GET", URL.toString(), "", "", publicKey, privateKey, host); log.debug("headers:" + headers.length); BufferedImage img = null;//from w w w . ja v a 2 s. c om HttpGet httpGet = new HttpGet(URL.toString()); httpGet.setHeaders(headers); HttpResponse response = client.execute(targetHost, httpGet, localcontext); int code = response.getStatusLine().getStatusCode(); log.info("url=" + url + " is " + code + "(OK=" + HttpURLConnection.HTTP_OK + ",MOVED=" + HttpURLConnection.HTTP_MOVED_TEMP + ")"); boolean isOK = (code == HttpURLConnection.HTTP_OK); boolean isFound = (code == HttpURLConnection.HTTP_MOVED_TEMP); boolean isErrorServer = (code == HttpURLConnection.HTTP_INTERNAL_ERROR); if (!isOK && !isFound & !isErrorServer) { throw new IOException(url + " cannot be read: " + code); } HttpEntity entity = response.getEntity(); if (entity != null) { log.debug("img=" + entity.getContent()); img = ImageIO.read(entity.getContent()); } return img; }
From source file:com.connectsdk.service.AirPlayService.java
@Override public void displayImage(final String url, String mimeType, String title, String description, String iconSrc, final LaunchListener listener) { Util.runInBackground(new Runnable() { @Override/* w ww . j a va 2s . c om*/ public void run() { ResponseListener<Object> responseListener = new ResponseListener<Object>() { @Override public void onSuccess(Object response) { LaunchSession launchSession = new LaunchSession(); launchSession.setService(AirPlayService.this); launchSession.setSessionType(LaunchSessionType.Media); Util.postSuccess(listener, new MediaLaunchObject(launchSession, AirPlayService.this)); } @Override public void onError(ServiceCommandError error) { Util.postError(listener, error); } }; String uri = getRequestURL("photo"); byte[] payload = null; try { URL imagePath = new URL(url); HttpURLConnection connection = (HttpURLConnection) imagePath.openConnection(); connection.setInstanceFollowRedirects(true); connection.setDoInput(true); connection.connect(); int responseCode = connection.getResponseCode(); boolean redirect = (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER); if (redirect) { String newPath = connection.getHeaderField("Location"); URL newImagePath = new URL(newPath); connection = (HttpURLConnection) newImagePath.openConnection(); connection.setInstanceFollowRedirects(true); connection.setDoInput(true); connection.connect(); } InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); ByteArrayOutputStream stream = new ByteArrayOutputStream(); myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); payload = stream.toByteArray(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } ServiceCommand<ResponseListener<Object>> request = new ServiceCommand<ResponseListener<Object>>( AirPlayService.this, uri, payload, responseListener); request.setHttpMethod(ServiceCommand.TYPE_PUT); request.send(); } }); }
From source file:org.sakaiproject.commons.tool.entityprovider.CommonsEntityProvider.java
@EntityCustomAction(action = "getUrlMarkup", viewKey = EntityView.VIEW_LIST) public ActionReturn getUrlMarkup(OutputStream outputStream, EntityView view, Map<String, Object> params) { String userId = getCheckedUser(); String urlString = (String) params.get("url"); if (StringUtils.isBlank(urlString)) { throw new EntityException("No url supplied", "", HttpServletResponse.SC_BAD_REQUEST); }//w w w . j a v a 2 s .co m try { CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); URL url = new URL(urlString); URLConnection c = url.openConnection(); if (c instanceof HttpURLConnection) { HttpURLConnection conn = (HttpURLConnection) c; conn.setRequestProperty("User-Agent", USER_AGENT); conn.setInstanceFollowRedirects(false); conn.connect(); String contentEncoding = conn.getContentEncoding(); String contentType = conn.getContentType(); int responseCode = conn.getResponseCode(); log.debug("Response code: {}", responseCode); int redirectCounter = 1; while ((responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_SEE_OTHER) && redirectCounter < 20) { String newUri = conn.getHeaderField("Location"); log.debug("{}. New URI: {}", responseCode, newUri); String cookies = conn.getHeaderField("Set-Cookie"); url = new URL(newUri); c = url.openConnection(); conn = (HttpURLConnection) c; conn.setInstanceFollowRedirects(false); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Cookie", cookies); conn.connect(); contentEncoding = conn.getContentEncoding(); contentType = conn.getContentType(); responseCode = conn.getResponseCode(); log.debug("Redirect counter: {}", redirectCounter); log.debug("Response code: {}", responseCode); redirectCounter += 1; } if (contentType != null && (contentType.startsWith("text/html") || contentType.startsWith("application/xhtml+xml") || contentType.startsWith("application/xml"))) { String mimeType = contentType.split(";")[0].trim(); log.debug("mimeType: {}", mimeType); log.debug("encoding: {}", contentEncoding); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); String line = null; while ((line = reader.readLine()) != null) { writer.write(line); } return new ActionReturn(contentEncoding, mimeType, outputStream); } else { log.debug("Invalid content type {}. Throwing bad request ...", contentType); throw new EntityException("Url content type not supported", "", HttpServletResponse.SC_BAD_REQUEST); } } else { throw new EntityException("Url content type not supported", "", HttpServletResponse.SC_BAD_REQUEST); } } catch (MalformedURLException mue) { throw new EntityException("Invalid url supplied", "", HttpServletResponse.SC_BAD_REQUEST); } catch (IOException ioe) { throw new EntityException("Failed to download url contents", "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:at.spardat.xma.boot.transport.HTTPTransport.java
private Result getResourceImpl(IRtXMASessionClient session, URL url, long modifiedSince, String etag) throws CommunicationException { /* locals ---------------------------------- */ Result result = new Result(); int code = 0; HttpURLConnection conn;//from w w w . ja v a 2s.c o m /* locals ---------------------------------- */ try { conn = (HttpURLConnection) url.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier); } sendCookies(session, url, conn); if (etag != null) { conn.setRequestProperty("If-None-Match", etag); //$NON-NLS-1$ } String strUrl = url.toExternalForm(); if (url.getQuery() == null && (strUrl.endsWith(".jar") || strUrl.endsWith(".xml"))) { conn.setRequestProperty(Statics.HTTP_CACHE_CONTROL, Statics.HTTP_MAX_AGE + "=0"); //$NON-NLS-1$ } if (modifiedSince > 0) { // see sun bugid: 4397096 // if HTTP_Util library is used, the original method may also be used. // conn.setIfModifiedSince(modifiedSince); conn.setRequestProperty(Statics.strIfModifiedSince, HTTPTransport.httpDate(modifiedSince)); } conn.setRequestProperty(Statics.HTTP_ACCEPT, "*/*"); //$NON-NLS-1$ conn.setRequestProperty(Statics.HTTP_USER_AGENT, Statics.HTTP_USER_AGENT_NAME); } catch (IOException exc) { log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' form server:", exc); //$NON-NLS-1$ throw new ConnectException("error loading '" + url.toString() + "' form server:", exc); } try { code = conn.getResponseCode(); if (code == HttpURLConnection.HTTP_NOT_MODIFIED) { result.contentLength_ = 0; result.lastModified_ = conn.getLastModified(); if (result.lastModified_ <= 0) { result.lastModified_ = modifiedSince; } result.expirationDate_ = conn.getExpiration(); result.etag_ = conn.getHeaderField(Statics.strEtag); if (result.etag_ == null) { result.etag_ = etag; } log_.log(LogLevel.FINE, "resource not modified: {0}", url.toExternalForm()); //$NON-NLS-1$ } else if (code == HttpURLConnection.HTTP_OK) { result.contentLength_ = conn.getContentLength(); result.lastModified_ = conn.getLastModified(); result.expirationDate_ = conn.getExpiration(); result.etag_ = conn.getHeaderField(Statics.strEtag); result.transformations_ = conn.getHeaderField(Statics.TRANSFORM_HEADER); result.setBuffer(this.readOutput(conn)); if (result.contentLength_ < 0) { result.contentLength_ = result.buffer_.length; } } else if (code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_MOVED_PERM) { String location = conn.getHeaderField(Statics.HTTP_LOCATION); throw new RedirectException("redirect received from " + url.toString() + " to " + location, code, location); } else { if (code < 500) throw new ConnectException("error loading '" + url.toString() + "' from the server:", code); else throw new ServerException("error loading '" + url.toString() + "' from the server:", code); } readCookies(session, url, conn); } catch (RedirectException re) { throw re; } catch (CommunicationException ce) { if (code != 0) log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$ log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ce); //$NON-NLS-1$ throw ce; } catch (Exception ex) { if (code != 0) log_.log(LogLevel.WARNING, "http returncode: {0}", Integer.toString(code)); //$NON-NLS-1$ log_.log(LogLevel.WARNING, "error loading '" + url.toString() + "' from the server:", ex); //$NON-NLS-1$ if (code < 500) throw new ConnectException("error loading '" + url.toString() + "' from the server:", ex); else throw new ServerException("error loading '" + url.toString() + "' from the server:", ex); } return result; }
From source file:net.caseif.flint.steel.lib.net.gravitydevelopment.updater.Updater.java
private URL followRedirects(String location) throws IOException { URL resourceUrl, base, next;/*from w w w . j av a2 s. co m*/ HttpURLConnection conn; String redLoc; while (true) { resourceUrl = new URL(location); conn = (HttpURLConnection) resourceUrl.openConnection(); conn.setConnectTimeout(15000); conn.setReadTimeout(15000); conn.setInstanceFollowRedirects(false); conn.setRequestProperty("User-Agent", "Mozilla/5.0..."); switch (conn.getResponseCode()) { case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: redLoc = conn.getHeaderField("Location"); base = new URL(location); next = new URL(base, redLoc); // Deal with relative URLs location = next.toExternalForm(); continue; } break; } return conn.getURL(); }
From source file:org.jboss.as.test.integration.web.formauth.FormAuthUnitTestCase.java
public HttpPost doSecureGetWithLogin(String path, String username, String password) throws Exception { log.info("+++ doSecureGetWithLogin : " + path); URL url = new URL(baseURLNoAuth + path); HttpGet httpget = new HttpGet(url.toURI()); log.info("Executing request " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); int statusCode = response.getStatusLine().getStatusCode(); Header[] errorHeaders = response.getHeaders("X-NoJException"); assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK); assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0); HttpEntity entity = response.getEntity(); if ((entity != null) && (entity.getContentLength() > 0)) { String body = EntityUtils.toString(entity); assertTrue("Redirected to login page", body.indexOf("j_security_check") > 0); } else {/*from w w w . ja v a 2s .co m*/ fail("Empty body in response"); } String sessionID = null; for (Cookie k : httpclient.getCookieStore().getCookies()) { if (k.getName().equalsIgnoreCase("JSESSIONID")) sessionID = k.getValue(); } log.info("Saw JSESSIONID=" + sessionID); // Submit the login form HttpPost formPost = new HttpPost(baseURLNoAuth + "j_security_check"); formPost.addHeader("Referer", baseURLNoAuth + "restricted/login.html"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("j_username", username)); formparams.add(new BasicNameValuePair("j_password", password)); formPost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8")); log.info("Executing request " + formPost.getRequestLine()); HttpResponse postResponse = httpclient.execute(formPost); statusCode = postResponse.getStatusLine().getStatusCode(); errorHeaders = postResponse.getHeaders("X-NoJException"); assertTrue("Should see HTTP_MOVED_TEMP. Got " + statusCode, statusCode == HttpURLConnection.HTTP_MOVED_TEMP); assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0); EntityUtils.consume(postResponse.getEntity()); // Follow the redirect to the SecureServlet Header location = postResponse.getFirstHeader("Location"); URL indexURI = new URL(location.getValue()); HttpGet war1Index = new HttpGet(url.toURI()); log.info("Executing request " + war1Index.getRequestLine()); HttpResponse war1Response = httpclient.execute(war1Index); statusCode = war1Response.getStatusLine().getStatusCode(); errorHeaders = war1Response.getHeaders("X-NoJException"); assertTrue("Wrong response code: " + statusCode, statusCode == HttpURLConnection.HTTP_OK); assertTrue("X-NoJException(" + Arrays.toString(errorHeaders) + ") is null", errorHeaders.length == 0); HttpEntity war1Entity = war1Response.getEntity(); if ((war1Entity != null) && (entity.getContentLength() > 0)) { String body = EntityUtils.toString(war1Entity); if (body.indexOf("j_security_check") > 0) fail("Get of " + indexURI + " redirected to login page"); } else { fail("Empty body in response"); } return formPost; }
From source file:org.jboss.test.cluster.multicfg.web.test.ScopedTestCase.java
/** * Test ability for a FORM auth based app to have failover without requiring * a new sign-on//from w ww . j a va2 s . co m * * This test will not pass until a FormAuthenticator that makes * use of cached usernames and passwords is available. * * @throws Exception */ public void badtestFormAuthFailover() throws Exception { log.info("+++ testFormAuthFailover"); // Start by accessing the war's protected url HttpClient client = new HttpClient(); String body = makeGet(client, baseURL0_ + protectedUrl_); if (body.indexOf("j_security_check") < 0) fail("get of " + protectedUrl_ + " not redirected to login page"); HttpState state = client.getState(); Cookie[] cookies = state.getCookies(); String sessionID = null; for (int c = 0; c < cookies.length; c++) { Cookie k = cookies[c]; if (k.getName().equalsIgnoreCase("JSESSIONID")) sessionID = k.getValue(); } log.debug("Saw JSESSIONID=" + sessionID); // Submit the login form PostMethod formPost = new PostMethod(baseURL0_ + securityCheckUrl_); formPost.addRequestHeader("Referer", baseURL0_ + loginFormUrl_); formPost.addParameter("j_username", "admin"); formPost.addParameter("j_password", "admin"); int responseCode = client.executeMethod(formPost.getHostConfiguration(), formPost, state); String response = formPost.getStatusText(); log.debug("responseCode=" + responseCode + ", response=" + response); assertTrue("Saw HTTP_MOVED_TEMP(" + responseCode + ")", responseCode == HttpURLConnection.HTTP_MOVED_TEMP); // Follow the redirect to the index.html page body = makeGet(client, baseURL0_ + protectedUrl_); if (body.indexOf("j_security_check") > 0) fail("get of " + baseURL0_ + protectedUrl_ + " redirected to login page"); // Switch to the second server SessionTestUtil.setCookieDomainToThisServer(client, servers_[1]); sleepThread(DEFAULT_SLEEP); // Now try getting the protected url on the second server body = makeGet(client, baseURL1_ + protectedUrl_); if (body.indexOf("j_security_check") > 0) fail("get of " + baseURL1_ + protectedUrl_ + " redirected to login page"); }