您的位置:首页 > 理论基础 > 计算机网络

怎么利用HttpURLConnection向服务器发送键值对

2015-11-23 19:15 585 查看
一般情况下HttpURLConnection利用Get方法可以直接通过url向服务器发送键值对。这种方式下数据往往是以url?name=value&name1=value1.....的形式向服务器传送数据的。利用OutputStream直接向服务器写入字节流即可。但是对于一些比较隐秘的数据,用户并不想通过这种显示的方式向数据库传送数据。所有这时候即使是少量的数据也要用post方式来传送。对于post传递键值对一般有两种方式,一种是直接放在http头中(也就是所谓的首部行了)向服务器传送,另一种是放在数据流中OutputStream。下面是第一种传送方式的简单介绍:

方法很简单,在客户端将键值对存储在http首部行中,然后在服务器端使用getHeader()的方法读取键值对。下面是具体代码部分:

import java.net.HttpURLConnection;
import java.net.URL;
public class HttpConnectonTest {
public static void main(String[] agrs){
String usrStr = "http://localhost:8080/LearningPlatfromServer//servlet/RegisterServlet";
try {
URL url = new URL(usrStr);//创建一个URL
HttpURLConnection connection  = (HttpURLConnection)url.openConnection();//通过该url获得与服务器的连接
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");//设置请求方式为post
connection.setConnectTimeout(3000);//设置超时为3秒
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置传送类型
connection.setRequestProperty("user_name", "yangwan");
connection.setRequestProperty("user_password", "12345");
connection.setRequestProperty("user_email", "632024528@qq.con");
//post方法要传送的键值对
connection.connect();
int responseCode = connection.getResponseCode();//获得连接的状态码
if(responseCode == 200){//200表示连接服务器成功,且获得正确响应
System.out.println("连接服务器成功");
}else{
System.out.println("连接服务器失败"+responseCode);
}
} catch (Exception  e) {
e.printStackTrace();
}
}
}
代码部分还是很好理解的。该服务器端是MyEclipse创建的一个Web Service,应用本地服务器tomcat.请求url是服务器端的一个Servlet。下面是这个Servlet中的响应客户端请求的具体代码:

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterServlet extends HttpServlet {
public RegisterServlet() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getHeader("user_name");
String userPassword = request.getHeader("user_password");
String userEmail = request.getHeader("user_email");
System.out.println("user_name: "+userName);
System.out.println("user_password: "+userPassword);
System.out.println("user_email: "+userEmail);
}
public void init() throws ServletException {
}
}
这样在客户端(Eclipse)中运行HttpURLConnection的那段程序后,在服务器端(MyEclipse)中的控制台就会出现下面的结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: