Description
Returns the cookies returned by the server on accessing the URL.
License
Open Source License
Parameter
Parameter | Description |
---|
url | a parameter |
Exception
Parameter | Description |
---|
IOException | an exception |
Return
The cookies as string, build by .
Declaration
public static String getCookies(final URL url) throws IOException
Method Source Code
//package com.java2s;
/**//from w w w. j a v a2 s.com
*
* BibSonomy-Web-Common - A blue social bookmark and publication sharing system.
*
* Copyright (C) 2006 - 2011 Knowledge & Data Engineering Group,
* University of Kassel, Germany
* http://www.kde.cs.uni-kassel.de/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class Main {
/**
* The user agent used for all requests with {@link HttpURLConnection}.
*/
private static final String USER_AGENT_PROPERTY_VALUE = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)";
private static final String USER_AGENT_HEADER_NAME = "User-Agent";
/**
* Returns the cookies returned by the server on accessing the URL.
* The format of the returned cookies is as
*
*
* @param url
* @return The cookies as string, build by {@link #buildCookieString(List)}.
* @throws IOException
*/
public static String getCookies(final URL url) throws IOException {
final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setAllowUserInteraction(false);
urlConn.setDoInput(true);
urlConn.setDoOutput(false);
urlConn.setUseCaches(false);
urlConn.setRequestProperty(USER_AGENT_HEADER_NAME, USER_AGENT_PROPERTY_VALUE);
urlConn.connect();
final List<String> cookies = urlConn.getHeaderFields().get("Set-Cookie");
urlConn.disconnect();
return buildCookieString(cookies);
}
/**
* Builds a cookie string as used in the HTTP header.
*
* @param cookies - a list of key/value pairs
* @return The cookies folded into a string.
*/
public static String buildCookieString(final List<String> cookies) {
final StringBuffer result = new StringBuffer();
if (cookies != null) {
for (final String cookie : cookies) {
if (result.length() != 0)
result.append(";");
result.append(cookie);
}
}
return result.toString();
}
}
Related
- storeCookies(HttpURLConnection connection)