HttpUrlConnection Post提交数据到服务器、并得到服务器返回的数据
2015-09-18 14:07
671 查看
public class HttpUtils {
private static String PATH = "http://bdfngdg:8080/myhttp/servlet/LoginAction"; // 服务端地址
private static URL url;
public HttpUtils() {
super();
}
// 静态代码块实例化url
static {
try {
url = new URL(PATH);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* 发送消息体到服务端
*
* @param params
* @param encode
* @return
*/
public static String sendPostMessage(Map<String, String> params,
String encode) {
StringBuilder stringBuilder = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
try {
stringBuilder
.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
try {
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setRequestMethod("POST"); // 以post请求方式提交
urlConnection.setDoInput(true); // 读取数据
urlConnection.setDoOutput(true); // 向服务器写数据
// 获取上传信息的大小和长度
byte[] myData = stringBuilder.toString().getBytes();
// 设置请求体的类型是文本类型,表示当前提交的是文本数据
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length",
String.valueOf(myData.length));
// 获得输出流,向服务器输出内容
OutputStream outputStream = urlConnection.getOutputStream();
// 写入数据
outputStream.write(myData, 0, myData.length);
outputStream.close();
// 获得服务器响应结果和状态码
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
// 取回响应的结果
return changeInputStream(urlConnection.getInputStream(),
encode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
/**
* 将一个输入流转换成指定编码的字符串
*
* @param inputStream
* @param encode
* @return
*/
private static String changeInputStream(InputStream inputStream,
String encode) {
// 内存流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = null;
if (inputStream != null) {
try {
while ((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
result = new String(byteArrayOutputStream.toByteArray(), encode);
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("username", "admin");
map.put("password", "123456");
String result = sendPostMessage(map, "UTF-8");
System.out.println(">>>" + result);
}
}
我们再创建一个服务端工程,一个web project,这里创建一个myhttp的工程,先给它创建一个servlet,用来接收参数访问。
创建的servlet配置如下:
[html] view
plaincopy
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginAction</servlet-name>
<servlet-class>com.login.manager.LoginAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginAction</servlet-name>
<url-pattern>/servlet/LoginAction</url-pattern>
</servlet-mapping>
建立的LoginAction.java类继承HttpServlet:
[html] view
plaincopy
package com.login.manager;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginAction extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginAction() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String userName = request.getParameter("username");
String passWord = request.getParameter("password");
System.out.println("userName:"+userName);
System.out.println("passWord:"+passWord);
if(userName.equals("admin") && passWord.equals("123456")){
//返回给android客户端的值就是login successful!
out.print("login successful!");
}else{
out.print("login failed");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
private static String PATH = "http://bdfngdg:8080/myhttp/servlet/LoginAction"; // 服务端地址
private static URL url;
public HttpUtils() {
super();
}
// 静态代码块实例化url
static {
try {
url = new URL(PATH);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* 发送消息体到服务端
*
* @param params
* @param encode
* @return
*/
public static String sendPostMessage(Map<String, String> params,
String encode) {
StringBuilder stringBuilder = new StringBuilder();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
try {
stringBuilder
.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
try {
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setRequestMethod("POST"); // 以post请求方式提交
urlConnection.setDoInput(true); // 读取数据
urlConnection.setDoOutput(true); // 向服务器写数据
// 获取上传信息的大小和长度
byte[] myData = stringBuilder.toString().getBytes();
// 设置请求体的类型是文本类型,表示当前提交的是文本数据
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length",
String.valueOf(myData.length));
// 获得输出流,向服务器输出内容
OutputStream outputStream = urlConnection.getOutputStream();
// 写入数据
outputStream.write(myData, 0, myData.length);
outputStream.close();
// 获得服务器响应结果和状态码
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
// 取回响应的结果
return changeInputStream(urlConnection.getInputStream(),
encode);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
/**
* 将一个输入流转换成指定编码的字符串
*
* @param inputStream
* @param encode
* @return
*/
private static String changeInputStream(InputStream inputStream,
String encode) {
// 内存流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = null;
if (inputStream != null) {
try {
while ((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
result = new String(byteArrayOutputStream.toByteArray(), encode);
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("username", "admin");
map.put("password", "123456");
String result = sendPostMessage(map, "UTF-8");
System.out.println(">>>" + result);
}
}
我们再创建一个服务端工程,一个web project,这里创建一个myhttp的工程,先给它创建一个servlet,用来接收参数访问。
创建的servlet配置如下:
[html] view
plaincopy
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginAction</servlet-name>
<servlet-class>com.login.manager.LoginAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginAction</servlet-name>
<url-pattern>/servlet/LoginAction</url-pattern>
</servlet-mapping>
建立的LoginAction.java类继承HttpServlet:
[html] view
plaincopy
package com.login.manager;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginAction extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginAction() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String userName = request.getParameter("username");
String passWord = request.getParameter("password");
System.out.println("userName:"+userName);
System.out.println("passWord:"+passWord);
if(userName.equals("admin") && passWord.equals("123456")){
//返回给android客户端的值就是login successful!
out.print("login successful!");
}else{
out.print("login failed");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
相关文章推荐
- 飞鸽传书源码分析三-网络
- HttpClient使用post方式模拟表单提交数据到服务器并下载服务器文件
- xcode version7.0 禁用https
- Tcp协议理解
- Xcode7 网络请求报错:The resource could not be loaded because the App Transport Security policy requir
- xcode7.0-iOS9新特性之二:网络适配
- RedHat Linux网络配置过程笔记
- 计算机网络之局域网&以太网
- 计算机网络之局域网&以太网
- 【 Android官方文件读书笔记】连接网络
- ios网络判断的方式
- 计算机网络之数据链路层
- 计算机网络之数据链路层
- 计算机网络之概念解析
- 计算机网络之概念解析
- c++ Windows Socket实现最简单的C/S网络通信(TCP)
- 监测网络状态
- Http请求中Content-Type讲解以及在Spring MVC中的应用
- iOS9升级后退回HTTP协议
- 初次接触volley网络框架,进行初步封装使用