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的更多相关文章

  1. 客户端使用java,服务端使用c++的corba编程环境搭建

    我们先用c++实现服务端和客户端,然后再用java编写客户端. 1. 首先安装omniORB,omniORB提供 omniidl命令,以及一些头文件和库. omniORB一般是需要你自己进行编译. 2 ...

  2. C#使用Thrift简介,C#客户端和Java服务端相互交互

    C#使用Thrift简介,C#客户端和Java服务端相互交互 本文主要介绍两部分内容: C#中使用Thrift简介 用Java创建一个服务端,用C#创建一个客户端通过thrift与其交互. 用纯C#实 ...

  3. .net 客户端调用java或.net webservice进行soapheader验证

    .net 客户端调用java或.net webservice进行soapheader验证 最近项目中有业务需要跨平台调用web服务,客户端和服务器之间采用非对称加密来保证数据的安全性,webservi ...

  4. Java与WCF交互(二):WCF客户端调用Java web service【转】

    原文:http://www.cnblogs.com/downmoon/archive/2010/08/25/1807982.html 在上篇< Java与WCF交互(一):Java客户端调用WC ...

  5. 转载——Java与WCF交互(二):WCF客户端调用Java Web Service

    在上篇< Java与WCF交互(一):Java客户端调用WCF服务>中,我介绍了自己如何使用axis2生成java客户端的悲惨经历.有同学问起使用什么协议,经初步验证,发现只有wsHttp ...

  6. Hbase入门(五)——客户端(Java,Shell,Thrift,Rest,MR,WebUI)

    Hbase的客户端有原生java客户端,Hbase Shell,Thrift,Rest,Mapreduce,WebUI等等. 下面是这几种客户端的常见用法. 一.原生Java客户端 原生java客户端 ...

  7. RPC学习--C#使用Thrift简介,C#客户端和Java服务端相互交互

    本文主要介绍两部分内容: C#中使用Thrift简介 用Java创建一个服务端,用C#创建一个客户端通过thrift与其交互. 用纯C#实现Client和Server C#服务端,Java客户端 其中 ...

  8. Unity3D客户端和Java服务端使用Protobuf

    转自:http://blog.csdn.net/kakashi8841/article/details/17334493 前几天有位网友问我关于Unity3D里面使用Protobuf的方法,一时有事拖 ...

  9. HTTP请求中的Body构建——.NET客户端调用JAVA服务进行文件上传

    PS:今日的第二篇,当日事还要当日毕:)   http的POST请求发送的内容在Body中,因此有时候会有我们自己构建body的情况. JAVA使用http—post上传file时,spring框架中 ...

随机推荐

  1. 02--Java TCP Socket编程

    一.基础知识 1. TCP状态转换知识,可参考: http://www.cnblogs.com/qlee/archive/2011/07/12/2104089.html 2. TCP/IP五层模型   ...

  2. js--冒泡排序[由小到大]

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...

  3. [妙味Ajax]第二课:实例:留言板、瀑布流

    知识点总结 瀑布流原理(固定布局) 总宽度大小固定 每列宽度固定,比如LI,高度自动计算,每列使用float:left来布局 计算最短的一列,将Div插到最短的一列处(li里面包div)(getSho ...

  4. B/S和C/S的区别。

    现在软件开发的整体架构主要分为B/S架构与C/S架构 一,C/S——Client/Service:客户机/服务器模式: C/S (Client/Server)结构,即大家熟知的客户机和服务器结构.它是 ...

  5. Java中的使用了未经检查或不安全的操作

    1. javac -Xlint:unchecked MyMath.java检查不安全的操作 /***************************************************/ ...

  6. 数据库中,char 与 varchar2 的区别

    区别1: char 是定长的字符串 varchar2 是变长的字符串 区别2: name char(10)   zhangsan__ 如果实际长度不足10,使用空格补齐   name varchar2 ...

  7. Dokan官方说明文档

    Dokan 库Copyright(c) Hiroki Asakawa http://dokan-dev.net/en 什么是Dokan库================================ ...

  8. 7、Struts2实现文件上传和下载

    一.实现单个文件上传 1.创建如下web项目结构 2.在src下的com.action包下创建UploadAction.java package com.action; import java.io. ...

  9. jquery之全选全不选

    <input type="checkbox" onclick="selall(this)" />全选/全不选 <input type=&quo ...

  10. Linux中如何设置java环境变量

    这里介绍Linux下如何设置java环境变量. 工具/原料 Linux java环境变量 方法/步骤 1 查看java的安装路径   查看java执行路径   配置java环境变量   java的安装 ...