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(4)—— jQuery中的事件

    jQuery中的事件 [加载DOM] 在常规的JavaScript代码中,通常使用window.onload方法,在jQuery中,使用的是$(document).ready()方法.极大地提高了we ...

  2. hello world2

    GTD就是Getting Things Done的缩写,翻译过来就是"把事情做完",GTD的核心理念概括就是必须记录下来要做的事,然后整理安排并使自己一一去执行.GTD的五个核心原 ...

  3. Link方式导入java项目

    一.环境说明 我用的是eclipse3.3.2,并安装了myeclipse的插件. 二.工程文件说明 一共三个文件夹: javacode:存放Java源文件,包含多个子文件夹,每个子文件夹表示一个单独 ...

  4. AIDL机制实现进程间的通讯实例

    转载自:http://blog.csdn.net/cjjky/article/details/7562652 ======================================= 在Andr ...

  5. JavaScript 属性操作

    <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...

  6. discuz网站数据库迁移

    你的discuz网站数据库迁移,或者修改过改密码后,还要以下相关配置文件修改,才能不会出现1045错误 以windows系统为例:首先登陆远程桌面,在运行中输入cmd,单开命令模式,再输入  net ...

  7. ios打开系统自带APP

    打开系统自带app 打开系统设置: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root= ...

  8. assign retain copy

    举个例子: NSString *houseOfMM = [[NSString alloc] initWithString:'装梵几的三室两厅']; 上面一段代码会执行以下两个动作:  1 在堆上分配一 ...

  9. 二维离散平稳小波分解swt2

    对信号X进行N尺度平稳小波分解 [A,H,V,D]=swt2(X,N,'wname'); clc,clear all,close all; load woman; [cA,cH,cV,cD]=swt2 ...

  10. Infix to postfix without '(' and ')'

    #include<iostream> #include<stack> #include<string> #include<deque> using na ...