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. jquery的animate动画

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  2. scala集合和高级函数操作

    scala常用函数操作 reduceLeft   是将集合的元素从左向右进行所需要的相应操作,图以减法为例展示,表达的算法是 : 1-2-3-4-5 例: (1 to 5).reduceLeft(_ ...

  3. UITextField 设置 placeholder 的字体颜色方法

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Helvetica; color: #ff2608 } [_textField setValu ...

  4. SolrCloud今日大纲

    SolrCloud今日大纲(了解) ●    分布式集群系统基本概念 ●    SolrCloud入门 ●    SolrCloud搭建 ******************************* ...

  5. FZU 1627 Revival's road

    矩阵快速幂. #pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #inc ...

  6. socket编程——一个简单的例子

    从一个简单的使用TCP例子开始socket编程,其基本步骤如下: server                                                  client ++++ ...

  7. Apache Kafka开发入门指南(2)

    Apache Kafka目标是统一离线和在线处理,与Flume和Scribe相比较,Kafka在处理活动流数据方面更具优势.但是从架构的视野来看,Kafka与传统的消息系统(例如ActiveMQ或Ra ...

  8. 详解Bootstrap 定义按钮的样式(CSS)

    以下样式可用于<a>, <button>, 或 <input> 元素上: 更多关于Bootstrap 定义CSS样式的可查看:http://v2.bootcss.c ...

  9. javascript获取css中的样式值

    <body> <input type="button" id="btn" value="启动"/> <img ...

  10. jquery 固定导航

    网页代码: <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> & ...