Java代码
- public InputStreamgetStream(URLurl,Stringpost,URLcookieurl){
- HttpURLConnectionconnection;
- StringcookieVal=null ;
- StringsessionId="" ;
- Stringkey=null ;
- if (cookieurl!= null ){
- try {
- connection=(HttpURLConnection)cookieurl.openConnection();
- for ( int i= 1 ;(key=connection.getHeaderFieldKey(i))!= null ;i++){
- if (key.equalsIgnoreCase( "set-cookie" )){
- cookieVal=connection.getHeaderField(i);
- cookieVal=cookieVal.substring(0 ,cookieVal.indexOf( ";" ));
- sessionId=sessionId+cookieVal+";" ;
- }
- }
- InputStreamin=connection.getInputStream();
- System.out.println(sessionId);
- }catch (MalformedURLExceptione){
- System.out.println("urlcan'tconnection" );
- return null ;
- }catch (IOExceptione){
- System.out.println(e.getMessage());
- return null ;
- }
- }
- try {
- connection=(HttpURLConnection)url.openConnection();
- //这个要写在Post前,否则会取不到值,原因我不知道
- if (cookieurl!= null ){
- connection.setRequestProperty("Cookie" ,sessionId);
- }
- if (post!= "" ){
- connection.setDoOutput(true );
- connection.setRequestMethod("POST" );
- connection.getOutputStream().write(post.getBytes());
- connection.getOutputStream().flush();
- connection.getOutputStream().close();
- }
- int responseCode=connection.getResponseCode();
- int contentLength=connection.getContentLength();
- //System.out.println("Contentlength:"+contentLength);
- if (responseCode!=HttpURLConnection.HTTP_OK) return ( null );
- InputStreamin=connection.getInputStream();
- return (in);
- }
- catch (Exceptione){
- //System.out.println(e);
- //e.printStackTrace();
- return ( null );
- }
- }
转自:http://stephenjqj.javaeye.com/blog/477194