java中使用post提交数据


在向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 stub
		URL 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;
				else
					out.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;
	}
}


  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值