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

在Java中使用HttpURLConnection发送http客户端请求、服务器端返回信息、接受服务器端的信息

2016-09-05 09:54 826 查看
在最近的项目中要用到后台发送http请求(post)方式,获取服务器端返回哦信息。下面是自己做的一个简单的演示示例。

首先创建一个web工程,简单的一个web工程就好。里面创建两个jsp和一个servlet。其中jsp作为客户端,而servlet就相当于一个服务器端。

下面是其中的一个jsp1

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<form action="test2.jsp" method="post">

姓名:<input type="text" name="name" id="name"><br><br>

密码:<input type="password" name="password" id="password"><br><br>

<input type="submit" value="提交">

</form>

</body>

</html>

而下面是另一个jsp2主要用于发送http请求,和接受http返回的信息。其中为了方便我把所有的java代码都写在了jsp2中,理论上这样做是不规范的

<%@page import="java.io.ByteArrayOutputStream"%>

<%@page import="java.io.OutputStream"%>

<%@page import="java.net.HttpURLConnection"%>

<%@page import="java.net.URLEncoder"%>

<%@page import="java.net.URL"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

here
<%
// (/HTTP_URL_CONNECTION_TEST/myservlet)
String name = request.getParameter("name");
String password = request.getParameter("password");

//设置跳转的地的哈
String myurl = "http://localhost:8080/HTTP_URL_CONNECTION_TEST/myservlet";
URL url = new URL(myurl);
//报文组装
StringBuffer str = new StringBuffer();
str.append("name=").append(name).append("&").append("password=").append(password);
String sendResult = str.toString();
//加密哈
sendResult = URLEncoder.encode(sendResult);
//转换为byte类型
byte[] mydata = sendResult.getBytes();
//准备要连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置参数哈
connection.setConnectTimeout(3000);
connection.setRequestMethod("POST");
connection.setDoInput(true);// 表示从服务器获取数据
connection.setDoOutput(true);// 表示向服务器写数据

// 表示设置请求体的类型是文本类型
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(mydata.length));
// 获得输出流,向服务器输出数据
OutputStream outputStream = connection.getOutputStream();
outputStream.write(mydata, 0, mydata.length);
outputStream.close();

int responseCode = connection.getResponseCode();
String result = "";
if(responseCode==200)
{
ByteArrayOutputStream byteoutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;

if (connection.getInputStream() != null) {
System.out.println("get the information is not null");
while ((len = connection.getInputStream().read(data)) != -1) {
byteoutputStream.write(data, 0, len);
}
result = new String(byteoutputStream.toByteArray(), "utf-8");

}
else{
System.out.println("get the information is null");
}
//System.out.println("后代得到的数据:"+result);
}else{
System.out.println("出现错误!");
}
System.out.println("后代得到的数据:"+result);

%>

http的urlConnection->:<%=result+"总金额是"%>

</body>

</html>

好了上面jsp2就是发送http请求以及获取客户端的信息。

下面就是servlet充当一个服务器,可以来验证客户端发送的请求的信息。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//doGet(request, response);
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");

//获取客户端上传的
BufferedReader bufferedReader=request.getReader();
String line="";

StringBuffer stringBuffer=new StringBuffer();
while((line=bufferedReader.readLine())!=null)
{
stringBuffer.append(line);
}

//成功了啦
String test=stringBuffer.toString();
test=URLDecoder.decode(test);

System.out.println("这是王培力的测试哈"+test);

response.setHeader("Content-type","text/html;charset=UTF-8");//向浏览器发送一个响应头,设置浏览器的解码方式为UTF-8  
String data = "servlet information!";  
OutputStream stream = response.getOutputStream();  
stream.write(data.getBytes("UTF-8"));  

}

写的很简单,希望大家可以看得明白,对大家有所帮助
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: