java中使用post提交数据

来源:互联网 发布:平面设计需要哪些软件 编辑:程序博客网 时间:2024/05/10 04:45


在向Web服务器发送信息,通常有两个命令会被用到:GET与POST

区别:

1.get是从服务器获取数据,post是向服务器提交数据。

2.get是将参数的值添加到url的结尾处即可。但是参数的值应该遵循以下的规则:

  a.保留a-z,A-Z,0-9以及 . - * _ 。

  b.用+代替所有的空格。

  c.将其他的所有的字符都替换为UTF-8,将每个字节都编码为%后面紧跟一个两位的十六进制数字。(hello,world yang)=>hello%0x2ccworld+yang

  d.参数之间用&隔开。

  但是在java中post并不需要在url添加任何参数,而是从URLConnection中获得输出流,并将键值对写入输出流中。

3.get传送的数据有限制较小,post数据量比较大。

4.get安全性非常低,但是执行效率比post高。

java代码实现post如下:

public class testpost {     /**     * @param args     * @throws IOException     * Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件     * 在Java中,其配 置文件常为.properties文件,格式为文本文件,     * 文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释     */    public static void main(String[] args) throws IOException {//新建一个配置文件     Properties props=new Properties();     props.load(new FileInputStream("text.properties"));     String url=props.remove("url").toString();     String resp=Dopost(url,props);     System.out.println(resp);}private static String Dopost(String urlstring, Map<Object,Object> namevalueParis) throws IOException{// TODO Auto-generated method stubURL url=new URL(urlstring);URLConnection conn=url.openConnection();//允许获得输出流  通过输出流向服务器输出数据conn.setDoOutput(true);try{PrintWriter out=new PrintWriter(conn.getOutputStream());boolean first=true;for(Map.Entry<Object, Object> paris :namevalueParis.entrySet()){if(first)first=false;elseout.print('&');String name=paris.getKey().toString();String value=paris.getValue().toString();out.print(name);out.print('=');out.print(URLEncoder.encode(value,"UTF-8"));}}catch(IOException e){e.printStackTrace();}StringBuilder resp=new StringBuilder();try{Scanner in=new Scanner(conn.getInputStream());while(in.hasNext()){resp.append(in.nextLine());resp.append("\n");}}catch(IOException e){if(!connect instaneof HttpURLConnection) throw e;HttpURLConnection err=(HttpURLConnection) conn.getErrorStream();if(err==null)throw e;Scanner in=new Scanner(err);resp.append(in.nextLine());resp.append("\n");}return resp.toString();return null;}}


1 0