HttpURLConnection is subclass of URLConnection with support for HTTP-specific features, for example: open a connection, retrieve message and post data to server.
First of all, we need declare a global variable cookie:
1
|
public static String cookie = null ; |
Secondly, create a method GetCookieFromURL
, open a URL connection, read the cookie from opened connection and assign to global variable cookie
:
Please note the connection will be closed when method is finished(it’s one-off connection).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public static String GetCookieFromURL() { String result = null ; HttpURLConnection con = null ; try { URL url = new URL(urlName); con = (HttpURLConnection) (url.openConnection()); con.setConnectTimeout( 40000 ); con.setReadTimeout( 40000 ); con.setRequestMethod( "POST" ); con.setRequestProperty( "User-Agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)" ); con.setFollowRedirects( true ); con.setDoOutput( true ); con.setDoInput( true ); con.setUseCaches( false ); con.setAllowUserInteraction( false ); con.setRequestProperty( "Content-Type" , "application/x-www-form-urlencoded" ); con.setRequestProperty( "Content-Language" , "en-US" ); result = con.getHeaderField( "Set-Cookie" ); } catch (Exception e) { e.printStackTrace(); } finally { con.disconnect(); con = null ; } return result; } |
Third, we will open a different HTTP connection with cookies we got previously, prior to opening collection, use urlConn.setRequestProperty
set the cookie value, by this way, we are able to pass-by session across multiple requests, it’s very useful, for example, after login, we need use login session for a while to read and modify data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
public static byte [] getByteFromFile(String urlName) throws AvException { InputStream input = null ; HttpURLConnection urlConn = null ; try { urlConn = (HttpURLConnection) ( new URL(urlName).openConnection()); urlConn.setRequestMethod( "POST" ); urlConn.setRequestProperty( "User-Agent" , "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)" ); urlConn.setFollowRedirects( true ); urlConn.setDoOutput( true ); urlConn.setDoInput( true ); urlConn.setUseCaches( false ); urlConn.setAllowUserInteraction( false ); urlConn.setRequestProperty( "Content-Type" , "application/x-www-form-urlencoded" ); urlConn.setRequestProperty( "Content-Language" , "en-US" ); urlConn.setRequestProperty( "Cookie" , cookie); input = urlConn.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int bytesRead = 0 ; byte [] buffer = new byte [ 8192 ]; while ((bytesRead = input.read(buffer, 0 , buffer.length)) != - 1 ) { baos.write(buffer, 0 , bytesRead); } return baos.toByteArray(); } catch (Exception e) { throw new AvException( "maybe the internet is disable" , AvException.Type.INTERNET_DENIED); } finally { urlConn.disconnect(); urlConn = null ; } } |