提交表单信息

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


public class SendFormTest {
	public static void main(String[] args){
		//URLConnection connection =null;
		
		try {
			URL url=new URL("http://www.baidu.com");
			URLConnection connection = url.openConnection();	//取得连接
			connection.setDoInput(true);	//设置可以向服务器传送数据
			connection.setDoOutput(true);
			PrintWriter out=new PrintWriter(connection.getOutputStream());
			//添加待发送的参数到HashMap中
			HashMap map=new HashMap();
			
			map.put("username", "chelson233");
			map.put("password", "a1234567");
			map.put("phone", "a1234567");
			map.put("yanzheng", "PAMGT");
			map.put("address","dffewf");
			map.put("nice","ddfew");
			wrapHashMap(out,map);	//传送数据
			out.close();	//关闭输出流
			
			StringBuffer response=new StringBuffer();
			BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream()));
			//取得错误输入流
			InputStream err=((HttpURLConnection) connection).getErrorStream();
			in=new BufferedReader(new InputStreamReader(err));
			String line;
			while((line=in.readLine())!=null){	//获取所有的错误信息
				response.append(line+"\n");
			}
			in.close();
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	//将HashMap中的键值对作为表单参数发往服务器
	public  static void wrapHashMap(PrintWriter out, HashMap map) 
	throws UnsupportedEncodingException {
		// TODO Auto-generated method stub
		Set entrySet=map.entrySet();
		Iterator iter=entrySet.iterator();	//迭代访问map的键值对
		
		boolean firstElement =true;
		
		while(iter.hasNext()){
			Map.Entry<String, String> entry=(Map.Entry<String, String>)iter.next();
			if(!firstElement) {
				out.print("&" + entry.getKey() + "=");	//非第一个表单参数的传送方法
			} else {
				out.print(entry.getKey()+"=");//第一个表单参数的传送方法
			}
			//对字符进行编码
			out.print(URLEncoder.encode(entry.getValue()+"","UTF-8"));	
		}
		
	}
}


不知道错在哪里?应该怎么对应参数去传递呢?

提示的错误如下:

java.io.IOException: Server returned HTTP response code: 501 for URL: http://www.baidu.com
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1305)
at SendFormTest.main(SendFormTest.java:41)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值