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)