客户端 HttpUtils.java
package com.http.post; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map; public class HttpUtils { // 表示服务器端的url
private static String PATH = "http://192.168.0.100:8080/myhttp/servlet/LoginAction";
private static URL url; public HttpUtils() {
// TODO Auto-generated constructor stub
} static {
try {
url = new URL(PATH);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} /*
* params 填写的URL的参数 encode 字节编码
*/
public static String sendPostMessage(Map<String, String> params,
String encode) { StringBuffer stringBuffer = new StringBuffer(); if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
try {
stringBuffer
.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&"); } catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 删掉最后一个 & 字符
stringBuffer.deleteCharAt(stringBuffer.length() - 1);
System.out.println("-->>" + stringBuffer.toString()); try {
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true);// 从服务器获取数据
httpURLConnection.setDoOutput(true);// 向服务器写入数据 // 获得上传信息的字节大小及长度
byte[] mydata = stringBuffer.toString().getBytes();
// 设置请求体的类型
httpURLConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("Content-Lenth",
String.valueOf(mydata.length)); // 获得输出流,向服务器输出数据
OutputStream outputStream = (OutputStream) httpURLConnection
.getOutputStream();
outputStream.write(mydata); // 获得服务器响应的结果和状态码
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) { // 获得输入流,从服务器端获得数据
InputStream inputStream = (InputStream) httpURLConnection
.getInputStream();
return (changeInputStream(inputStream, encode)); } } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return "";
} /*
* // 把从输入流InputStream按指定编码格式encode变成字符串String
*/
public static String changeInputStream(InputStream inputStream,
String encode) { // ByteArrayOutputStream 一般叫做内存流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
if (inputStream != null) { try {
while ((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len); }
result = new String(byteArrayOutputStream.toByteArray(), encode); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } return result;
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, String> params = new HashMap<String, String>();
params.put("username", "admin");
params.put("password", "123");
String result = sendPostMessage(params, "utf-8");
System.out.println("-result->>" + result); } }
服务器端: LoginAction.java
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");
//客户端 HttpUtils并没有写request方法是post ,但服务器端可自动识别
String method = request.getMethod();
System.out.println("request method :"+method); PrintWriter out = response.getWriter();
String username = request.getParameter("username");
System.out.println("-username->>"+username); String password = request.getParameter("password");
System.out.println("-password->>"+password); if (username.equals("admin") && password.equals("123")) {
// 表示服务器段返回的结果
out.print("login is success !"); } else {
out.print("login is fail !");
} out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
客户端 HttpUtils.java的更多相关文章
- 客户端使用java,服务端使用c++的corba编程环境搭建
我们先用c++实现服务端和客户端,然后再用java编写客户端. 1. 首先安装omniORB,omniORB提供 omniidl命令,以及一些头文件和库. omniORB一般是需要你自己进行编译. 2 ...
- C#使用Thrift简介,C#客户端和Java服务端相互交互
C#使用Thrift简介,C#客户端和Java服务端相互交互 本文主要介绍两部分内容: C#中使用Thrift简介 用Java创建一个服务端,用C#创建一个客户端通过thrift与其交互. 用纯C#实 ...
- .net 客户端调用java或.net webservice进行soapheader验证
.net 客户端调用java或.net webservice进行soapheader验证 最近项目中有业务需要跨平台调用web服务,客户端和服务器之间采用非对称加密来保证数据的安全性,webservi ...
- Java与WCF交互(二):WCF客户端调用Java web service【转】
原文:http://www.cnblogs.com/downmoon/archive/2010/08/25/1807982.html 在上篇< Java与WCF交互(一):Java客户端调用WC ...
- 转载——Java与WCF交互(二):WCF客户端调用Java Web Service
在上篇< Java与WCF交互(一):Java客户端调用WCF服务>中,我介绍了自己如何使用axis2生成java客户端的悲惨经历.有同学问起使用什么协议,经初步验证,发现只有wsHttp ...
- Hbase入门(五)——客户端(Java,Shell,Thrift,Rest,MR,WebUI)
Hbase的客户端有原生java客户端,Hbase Shell,Thrift,Rest,Mapreduce,WebUI等等. 下面是这几种客户端的常见用法. 一.原生Java客户端 原生java客户端 ...
- RPC学习--C#使用Thrift简介,C#客户端和Java服务端相互交互
本文主要介绍两部分内容: C#中使用Thrift简介 用Java创建一个服务端,用C#创建一个客户端通过thrift与其交互. 用纯C#实现Client和Server C#服务端,Java客户端 其中 ...
- Unity3D客户端和Java服务端使用Protobuf
转自:http://blog.csdn.net/kakashi8841/article/details/17334493 前几天有位网友问我关于Unity3D里面使用Protobuf的方法,一时有事拖 ...
- HTTP请求中的Body构建——.NET客户端调用JAVA服务进行文件上传
PS:今日的第二篇,当日事还要当日毕:) http的POST请求发送的内容在Body中,因此有时候会有我们自己构建body的情况. JAVA使用http—post上传file时,spring框架中 ...
随机推荐
- 在SpringMVC的controller控制器中使用Servlet原生的API
只需要在控制器的方法里添加相应的Servlet 参数即可! 支持以下参数: 新建一个controller类,部分代码如下:(省略xml配置文件) @RequestMapping("servl ...
- BCTF Web Code–考脑洞,你能过么?
BCTF Web Code–考脑洞,你能过么? 1)打开链接,是一张图片 根据URL特点推断可能是有文件包含漏洞 2) 将jpg参数修改成index.php,查看源代码,发现base64编码后的代码 ...
- Javaweb 第7天 Servlet课程
Servlet课程 三日大纲 ● 网络概念,专业术语 ● Tomcat使用,发布网站,使用Myeclispe发布网站(搭建环境) ● 编写Servlet,Servlet生命周期 ● 用户注册,显示所有 ...
- doc 窗口操作图
doc 窗口操作图doc 窗口操作图vdoc 窗口操作图
- html5存储相关 coookie localstorage session storage
html5存储 coookie localstorage session storage
- Python创建多进程,用Queue传递信息
创建10个进程,分别计算0到1000各个区间的和,主进程汇总 __author__ = 'Administrator' # -*- coding:utf-8 -*- ''' @author:qiush ...
- Worker+MQ解惑
用Worker来保证数据的一致性,再加上MQ来便于水平扩展,也提升了Worker的效率.这就是传说中的Worker+MQ,又叫做可靠消息方式.另外,将任务的查询和执行分工,形成父子任务,达到真正的分布 ...
- [kuangbin带你飞]专题四 最短路练习 POJ 1797 Heavy Transportation
求每条道路的最大承载量 和上一道题差不多 就是松弛的规则从最大值变成了最小值 /* *********************************************** Author :Su ...
- ev=ev || window.event 与 ev = window.event || ev 区别
event是事件对象(也是window的属性),但不是标准的,只有IE支持.在W3C标准支持的浏览器下事件对象是引发事件函数的第一个参数,参数名随意.var oEvent = ev || event; ...
- 转载:Ubuntu下deb包的安装方法
转载:Ubuntu下deb包的安装方法,http://blog.csdn.net/kevinhg/article/details/5934462 deb是debian linus的安装格式,跟red ...