java httpurlconnection 发送cookie时,cookie要在Post前发送



Java代码 
  1. public InputStream getStream(URL url,String post,URL cookieurl){  
  2.         HttpURLConnection connection;  
  3.         String cookieVal null 
  4.         String sessionId “” 
  5.         String key=null 
  6.         if(cookieurl!=null){              
  7.             try 
  8.                 connection (HttpURLConnection)cookieurl.openConnection();  
  9.                 for (int 1(key connection.getHeaderFieldKey(i)) != nulli++  
  10.                     if (key.equalsIgnoreCase(“set-cookie”))  
  11.                         cookieVal connection.getHeaderField(i);  
  12.                         cookieVal cookieVal.substring(0cookieVal.indexOf(“;”));  
  13.                         sessionId sessionId+cookieVal+“;” 
  14.                      
  15.                  
  16.                 InputStream in connection.getInputStream();  
  17.                 System.out.println(sessionId);  
  18.             }catch(MalformedURLException e){  
  19.                 System.out.println(“url can’t connection”);  
  20.                 return null 
  21.             }catch(IOException e){  
  22.                 System.out.println(e.getMessage());  
  23.                 return null 
  24.              
  25.          
  26.   
  27.         try  
  28.             connection (HttpURLConnection)url.openConnection();  
  29.             //这个要写在Post前,否则会取不到值,原因我不知道  
  30.             if(cookieurl!=null){  
  31.                 connection.setRequestProperty(“Cookie”sessionId);  
  32.              
  33.             if(post!=“”){  
  34.                 connection.setDoOutput(true);  
  35.                 connection.setRequestMethod(“POST”);  
  36.                 connection.getOutputStream().write(post.getBytes());  
  37.                 connection.getOutputStream().flush();  
  38.                 connection.getOutputStream().close();  
  39.              
  40.             int responseCode connection.getResponseCode();  
  41.             int contentLength connection.getContentLength();  
  42.             // System.out.println(“Content length: “+contentLength);  
  43.             if (responseCode != HttpURLConnection.HTTP_OK return(null);  
  44.             InputStream in connection.getInputStream();  
  45.             return(in);  
  46.          
  47.         catch(Exception e)  
  48.             // System.out.println(e);  
  49.             // e.printStackTrace();  
  50.             return(null);  
  51.          
  52.           
  53.      

转自:http://stephenjqj.javaeye.com/blog/477194

JDK中的URLConnection参数详解



针对JDK中的URLConnection连接Servlet的问题,网上有虽然有所涉及,但是只是说明了某一个或几个问题,是以FAQ的方式来解决的,而且比较零散,现在对这个类的使用就本人在项目中的使用经验做如下总结: 

1:> URL请求的类别: 

分为二类,GET与POST请求。二者的区别在于: 

    
a:) get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet, 

    
b:) post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。 

2:> URLConnection的对象问题: 

URLConnection的对象,如下代码示例: 



//
下面的index.jsp由<servlet-mapping>映射到 

// 一个Servlet(com.quantanetwork.getClientDataServlet) 

// 该Servlet的注意点下边会提到 

URL url = new URL(http://localhost:8080/TestHttpURLConnectionPro/index.jsp); 



URLConnection rulConnection 
= url.openConnection();// 此处的urlConnection对象实际上是根据URL的 

          
// 请求协议(此处是http)生成的URLConnection类 

          
// 的子类HttpURLConnection,故此处最好将其转化 

          
// 为HttpURLConnection类型的对象,以便用到 

          
// HttpURLConnection更多的API.如下: 



HttpURLConnection httpUrlConnection 
= (HttpURLConnection) rulConnection; 





3:> HttpURLConnection对象参数问题 

// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 

// http正文内,因此需要设为true, 默认情况下是false; 

httpUrlConnection.setDoOutput(true); 



// 设置是否从httpUrlConnection读入,默认情况下是true; 

httpUrlConnection.setDoInput(true); 



// Post 请求不能使用缓存 

httpUrlConnection.setUseCaches(false); 



// 设定传送的内容类型是可序列化的java对象 

// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) 

httpUrlConnection.setRequestProperty(Content-typeapplication/x-java-serialized-object); 



// 设定请求的方法为”POST”,默认是GET 

httpUrlConnection.setRequestMethod(POST); 



// 连接,从上述第2条中url.openConnection()至此的配置必须要在connect之前完成, 

        httpUrlConnection.connect(); 





4:> 
HttpURLConnection连接问题: 


// 

此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法, 

// 所以在开发中不调用上述的connect()也可以)。 

OutputStream outStrm = httpUrlConnection.getOutputStream(); 



Http学习之使用HttpURLConnection发送post和get请求

最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。

在Java中可以使用HttpURLConnection发起这两种请求,了解此类,对于了解soap,和编写servlet的自动测试代码都有很大的帮助。

下面的代码简单描述了如何使用HttpURLConnection发起这两种请求,以及传递参数的方法:

public   class  HttpInvoker 

{


    

public   static   final  String GET_URL 
=   http://localhost:8080/welcome1
;


    

public   static   final  String POST_URL 
=   http://localhost:8080/welcome1
;


    

public   static   void  readContentFromGet() 
throws  IOException 

{

        

//  拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码

        String getURL 
=  GET_URL 
+   ?username=

                

+  URLEncoder.encode(
fat man utf-8 );

        URL getUrl 

=   new  URL(getURL);

        

//  根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,

        

//  返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection

        HttpURLConnection connection 
=  (HttpURLConnection) getUrl

                .openConnection();

        

//  进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到

        

//  服务器
        connection.connect();

        

//  取得输入流,并使用Reader读取

        BufferedReader reader 
=   new  BufferedReader(
new  InputStreamReader(

                connection.getInputStream()));

        System.out.println(

=============================
);

        System.out.println(

Contents of get request
);

        System.out.println(

=============================
);

        String lines;

        

while  ((lines 
=  reader.readLine()) 
!=   null
{

            System.out.println(lines);

        }



        reader.close();

        

//  断开连接
        connection.disconnect();

        System.out.println(

=============================
);

        System.out.println(

Contents of get request ends
);

        System.out.println(

=============================
);

    }




    

public   static   void  readContentFromPost() 
throws  IOException 

{

        

//  Post请求的url,与get不同的是不需要带参数

        URL postUrl 
=   new  URL(POST_URL);

        

//  打开连接
        HttpURLConnection connection 
=  (HttpURLConnection) postUrl

                .openConnection();

        

//  Output to the connection. Default is

        

//  false, set to true because post

        

//  method must write something to the

        

//  connection

        

//  设置是否向connection输出,因为这个是post请求,参数要放在

        

//  http正文内,因此需要设为true

        connection.setDoOutput(
true );

        

//  Read from the connection. Default is true.

        connection.setDoInput(
true );

        

//  Set the post method. Default is GET

        connection.setRequestMethod(
POST );

        

//  Post cannot use caches

        

//  Post 请求不能使用缓存

        connection.setUseCaches(
false );

        

//  This method takes effects to

        

//  every instances of this class.

        

//  URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。

        

//  connection.setFollowRedirects(true);


        

//  This methods only

        

//  takes effacts to this

        

//  instance.

        

//  URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数

        connection.setInstanceFollowRedirects(
true );

        

//  Set the content type to urlencoded,

        

//  because we will write

        

//  some URL-encoded content to the

        

//  connection. Settings above must be set before connect!

        

//  配置本次连接的Content-type,配置为application/x-www-form-urlencoded的

        

//  意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode

        

//  进行编码
        connection.setRequestProperty(
Content-Type ,

                

application/x-www-form-urlencoded
);

        

//  连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,

        

//  要注意的是connection.getOutputStream会隐含的进行connect。

        connection.connect();

        DataOutputStream out 

=   new  DataOutputStream(connection

                .getOutputStream());

        

//  The URL-encoded contend

        

//  正文,正文内容其实跟get的URL中’?’后的参数字符串一致

        String content 
=   firstname=   +  URLEncoder.encode(
一个大肥人 utf-8 );

        

//  DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面

        out.writeBytes(content); 


        out.flush();

        out.close(); 

//  flush and close

        BufferedReader reader 
=   new  BufferedReader(
new  InputStreamReader(

                connection.getInputStream()));

        String line;

        System.out.println(

=============================
);

        System.out.println(

Contents of post request
);

        System.out.println(

=============================
);

        

while  ((line 
=  reader.readLine()) 
!=   null
{

            System.out.println(line);

        }



        System.out.println(

=============================
);

        System.out.println(

Contents of post request ends
);

        System.out.println(

=============================
);

        reader.close();

        connection.disconnect();

    }




    




    

public   static   void  main(String[] args) 

{

        

//  TODO Auto-generated method stub


        
try  
{

            readContentFromGet();

            readContentFromPost();

        }

 
catch  (IOException e) 

{

            

//  TODO Auto-generated catch block

            e.printStackTrace();

        }



    }



}

上面的readContentFromGet()函数产生了一个get请求,传给servlet一个username参数,值为”fat
man”。
readContentFromPost()函数产生了一个post请求,传给servlet一个firstname参数,值为”一个大肥人”。
HttpURLConnection.connect函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。无论是post还是get,http请求实际上直到
HttpURLConnection
.getInputStream()这个函数里面才正式发送出去。

readContentFromPost()
中,顺序是重中之重,对connection对象的一切配置(那一堆set函数)都必须要在connect()函数执行之前完成。而对
outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。

http
请求实际上由两部分组成,一个是http头,所有关于此次http请求的配置都在http头里面定义,一个是正文content,在connect()函
数里面,会根据HttpURLConnection对象的配置值生成http头,因此在调用connect函数之前,就必须把所有的配置准备好。

紧接着http头的是http请求的正文,正文的内容通过outputStream写入,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,而是在流关闭后,根据输入的内容生成http正文。


此,http请求的东西已经准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个
输入流,用于读取服务器对于此次http请求的返回信息。由于http请求在getInputStream的时候已经发送出去了(包括http头和正
文),因此在getInputStream()函数之后对connection对象进行设置(对http头的信息进行修改)或者写入
outputStream(对正文进行修改)都是没有意义的了,执行这些操作会导致异常的发生。

转自:http://blog.csdn.net/pandazxx/archive/2007/06/18/1657109.aspx

[Java]读取文件方法大全

1、按字节读取文件内容
2、按字符读取文件内容
3、按行读取文件内容
4、随机读取文件内容

public class ReadFromFile {

    

    public static void readFileByBytes(String fileName) {

        File file = new File(fileName);

        InputStream in = null;

        try {

            System.out.println(以字节为单位读取文件内容,一次读一个字节:);

            // 一次读一个字节
            in = new FileInputStream(file);

            int tempbyte;

            while ((tempbyte = in.read()) != 1{

                System.out.write(tempbyte);

            }

            in.close();

        catch (IOException e) {

            e.printStackTrace();

            return;

        }

        try {

            System.out.println(以字节为单位读取文件内容,一次读多个字节:);

            // 一次读多个字节
            byte[] tempbytes = new byte[100];

            int byteread = 0;

            in = new FileInputStream(fileName);

            ReadFromFile.showAvailableBytes(in);

            // 读入多个字节到字节数组中,byteread为一次读入的字节数
            while ((byteread = in.read(tempbytes)) != 1{

                System.out.write(tempbytes, 0byteread);

            }

        catch (Exception e1) {

            e1.printStackTrace();

        finally {

            if (in != null{

                try {

                    in.close();

                catch (IOException e1) {

                }

            }

        }

    }

    

    public static void readFileByChars(String fileName) {

        File file = new File(fileName);

        Reader reader = null;

        try {

            System.out.println(以字符为单位读取文件内容,一次读一个字节:);

            // 一次读一个字符
            reader = new InputStreamReader(new FileInputStream(file));

            int tempchar;

            while ((tempchar = reader.read()) != 1{

                // 对于windows下,\r\n这两个字符在一起时,表示一个换行。

                // 但如果这两个字符分开显示时,会换两次行。

                // 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
                if (((chartempchar) != \r{

                    System.out.print((chartempchar);

                }

            }

            reader.close();

        catch (Exception e) {

            e.printStackTrace();

        }

        try {

            System.out.println(以字符为单位读取文件内容,一次读多个字节:);

            // 一次读多个字符
            char[] tempchars = new char[30];

            int charread = 0;

            reader = new InputStreamReader(new FileInputStream(fileName));

            // 读入多个字符到字符数组中,charread为一次读取字符数
            while ((charread = reader.read(tempchars)) != 1{

                // 同样屏蔽掉\r不显示
                if ((charread == tempchars.length)

                        && (tempchars[tempchars.length  1!= \r)) {

                    System.out.print(tempchars);

                else {

                    for (int = 0< charread; i++{

                        if (tempchars[i] == \r{

                            continue;

                        else {

                            System.out.print(tempchars[i]);

                        }

                    }

                }

            }

        catch (Exception e1) {

            e1.printStackTrace();

        finally {

            if (reader != null{

                try {

                    reader.close();

                catch (IOException e1) {

                }

            }

        }

    }

    

    public static void readFileByLines(String fileName) {

        File file = new File(fileName);

        BufferedReader reader = null;

        try {

            System.out.println(以行为单位读取文件内容,一次读一整行:);

            reader = new BufferedReader(new FileReader(file));

            String tempString = null;

            int line = 1;

            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null{

                // 显示行号
                System.out.println(line  + line +  + tempString);

                line++;

            }

            reader.close();

        catch (IOException e) {

            e.printStackTrace();

        finally {

            if (reader != null{

                try {

                    reader.close();

                catch (IOException e1) {

                }

            }

        }

    }

    

    public static void readFileByRandomAccess(String fileName) {

        RandomAccessFile randomFile = null;

        try {

            System.out.println(随机读取一段文件内容:);

            // 打开一个随机访问文件流,按只读方式
            randomFile = new RandomAccessFile(fileName, r);

            // 文件长度,字节数
            long fileLength = randomFile.length();

            // 读文件的起始位置
            int beginIndex = (fileLength > 4? 4 0;

            // 将读文件的开始位置移到beginIndex位置。
            randomFile.seek(beginIndex);

            byte[] bytes = new byte[10];

            int byteread = 0;

            // 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。

            // 将一次读取的字节数赋给byteread
            while ((byteread = randomFile.read(bytes)) != 1{

                System.out.write(bytes, 0byteread);

            }

        catch (IOException e) {

            e.printStackTrace();

        finally {

            if (randomFile != null{

                try {

                    randomFile.close();

                catch (IOException e1) {

                }

            }

        }

    }

    

    private static void showAvailableBytes(InputStream in) {

        try {

            System.out.println(当前字节输入流中的字节数为: + in.available());

        catch (IOException e) {

            e.printStackTrace();

        }

    }

    public static void main(String[] args) {

        String fileName = C:/temp/newTemp.txt;

        ReadFromFile.readFileByBytes(fileName);

        ReadFromFile.readFileByChars(fileName);

        ReadFromFile.readFileByLines(fileName);

        ReadFromFile.readFileByRandomAccess(fileName);

    }

}

5、将内容追加到文件尾部

public class AppendToFile {

    

    public static void appendMethodA(String fileName, String content) {

        try {

            // 打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, rw);

            // 文件长度,字节数
            long fileLength = randomFile.length();

            //将写文件指针移到文件尾。
            randomFile.seek(fileLength);

            randomFile.writeBytes(content);

            randomFile.close();

        catch (IOException e) {

            e.printStackTrace();

        }

    }

    

    public static void appendMethodB(String fileName, String content) {

        try {

            //打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);

            writer.write(content);

            writer.close();

        catch (IOException e) {

            e.printStackTrace();

        }

    }

    public static void main(String[] args) {

        String fileName = C:/temp/newTemp.txt;

        String content = new append!;

        //按方法A追加文件
        AppendToFile.appendMethodA(fileName, content);

        AppendToFile.appendMethodA(fileName, append end. \n);

        //显示文件内容
        ReadFromFile.readFileByLines(fileName);

        //按方法B追加文件
        AppendToFile.appendMethodB(fileName, content);

        AppendToFile.appendMethodB(fileName, append end. \n);

        //显示文件内容
        ReadFromFile.readFileByLines(fileName);

    }

}

 

增强J2ME的String能力——分割字符串(附源代码)

从JDK1.4以后,String类中新增了split方法来实现字符串的分割,但是在J2ME中却没有该方法(MIDP2.0中也没有实现),但是在实际使用过程中,有些时候的确要用到这种操作,这里将我以前实现的一段代码和大家共享,不足之处大家多提意见和建议:

 private static String[] split(String
original,String regex)
 {
  //取子串的起始位置
  int startIndex = 0;
  //将结果数据先放入Vector中
  Vector v = new Vector();
  //返回的结果字符串数组
  String[] str = null;
 
  //存储取子串时起始位置
  int index = 0;
  //获得匹配子串的位置
  startIndex = original.indexOf(regex);
 
  //System.out.println(“0” + startIndex);
 
  //如果起始字符串的位置小于字符串的长度,则证明没有取到字符串末尾。
  //-1代表取到了末尾
  while(startIndex <
original.length() && startIndex !=
-1)
  {
   String temp =
original.substring(index,startIndex);
 
  
System.out.println(”    
”  + startIndex);
 
   //取子串
   v.addElement(temp);
           
//设置取子串的起始位置
   index = startIndex +
regex.length();
   //获得匹配子串的位置
   startIndex =
original.indexOf(regex,startIndex + regex.length());
  }
  //取结束的子串
  v.addElement(original.substring(index + 1 –
regex.length()));
 
  //将Vector对象转换成数组
  str = new String[v.size()];
  for(int i=0;i<v.size();i++)
  {
   str[i] =
(String)v.elementAt(i);
  }
  //返回生成的数组
  return str;
}