HttpClient中的client和server相互调用的两个例子
1.例子一:新加web工程,导入jar包
1.1server:
package com.zl.http.test1;
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;
/**
*
* @author zenglong
*
* @Description: 为了验证http接口的调用,编写了一个模拟的http接口
*
*/
public class HttpServer1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("gbk");
PrintWriter out = response.getWriter();
String param1 = request.getParameter("param1");
out.println("param1=" + param1);
String param2 = request.getParameter("param2");
out.println("param2=" + param2);
if (param1 == null || "".equals("param1") || param1.length() <= 0) {
out.println("http call failed,参数param1不能为空,程序退出");
} else if (param2 == null || "".equals("param2")
|| param2.length() <= 0) {
out.println("http call failed,参数param2不能为空,程序退出");
} else {
out.println("---http call success---");
}
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
1.2:
package com.zl.http.test1;
import java.io.IOException;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author zenglong
*
* @Description: 以get/post的方式发送数据到指定的http接口---利用httpclient.jar包---HTTP接口的调用
*
*/
public class HttpClient1 {
private static final Log log = LogFactory
.getLog(HttpClient1.class);
/**
* get方式
* @param param1
* @param param2
* @return
*/
public static String getHttp(String param1,String param2){
String responseMsg = "";
// 1.构造HttpClient的实例
HttpClient httpClient = new HttpClient();
// 用于测试的http接口的url
String url="http://localhost:8080/UpDown/httpServer?param1="+param1+"¶m2="+param2;
// 2.创建GetMethod的实例
GetMethod getMethod = new GetMethod(url);
// 使用系统系统的默认的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try {
//3.执行getMethod,调用http接口
httpClient.executeMethod(getMethod);
//4.读取内容
byte[] responseBody = getMethod.getResponseBody();
//5.处理返回的内容
responseMsg = new String(responseBody);
log.info(responseMsg);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//6.释放连接
getMethod.releaseConnection();
}
return responseMsg;
}
/**
* post方式
* @param param1
* @param param2
* @return
*/
public static String postHttp(String param1,String param2) {
String responseMsg = "";
//1.构造HttpClient的实例
HttpClient httpClient=new HttpClient();
httpClient.getParams().setContentCharset("GBK");
String url="http://localhost:8080/http/httpServer";
//2.构造PostMethod的实例
PostMethod postMethod=new PostMethod(url);
//3.把参数值放入到PostMethod对象中
//方式1:
/* NameValuePair[] data = { new NameValuePair("param1", param1),
new NameValuePair("param2", param2) };
postMethod.setRequestBody(data);*/
//方式2:
postMethod.addParameter("param1", param1);
postMethod.addParameter("param2", param2);
try {
// 4.执行postMethod,调用http接口
httpClient.executeMethod(postMethod);//200
//5.读取内容
responseMsg = postMethod.getResponseBodyAsString().trim();
log.info(responseMsg);
//6.处理返回的内容
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//7.释放连接
postMethod.releaseConnection();
}
return responseMsg;
}
/**
* 测试的main方法
* @param args
*/
public static void main(String[] args) {
String param1="111";
String param2="222";
//get
// System.out.println("get方式调用http接口\n"+getHttp(param1, param2));
//post
System.out.println("post方式调用http接口\n"+postHttp(param1,param2));
}
}
2.例子二:
新建web工程,导入jar
2.1 server
package com.zl.http.json;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author zenglong
*
* @Description: 模拟的一个Http服务,处理客户端的post请求
*
*/
public class HttpServer2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String inJson = null;// 保存HTTP客户端请求报文
String outJson = null;// 保存HTTP服务端输出报文
// 获得输人报文然后打印出来
inJson = getInJson(request);
System.out
.println("\nauthor<pantp>===========服务端日志----POST方式接收HTTP请求,HTTP服务端收到的请求报文如下:==========\n");
System.out.println(inJson);
System.out
.println("\nauthor<pantp>=================================================================\n");
// 以下代码部分获得请求报文,然后去做校验,转换以及其他的调用其他的业务逻辑等,这里就不管它
// ........................................................................
// 下面部分是输出部分的处理
outJson = "{\"服务器准备数据\": {\"code\": \"0\",\"message\": \"成功\",\"data\": \"12345\"}}";// 输出不部分也以JSON格式的字符串输出,这里我就写死
response.setContentType("application/json; charset=UTF-8");
response.getWriter().print(outJson);
}
// 获得请求的报文,并作简单的校验
public String getInJson(HttpServletRequest request) throws IOException {
byte buffer[] = new byte[64 * 1024];
InputStream in = request.getInputStream();// 获取输入流对象
int len = in.read(buffer);
// 必须对数组长度进行判断,否则在new byte[len]会报NegativeArraySizeException异常
if (len < 0) {
throw new IOException("请求报文为空");
}
String encode = request.getCharacterEncoding();// 获取请求头编码
// 必须对编码进行校验,否则在new String(data, encode);会报空指针异常
if (null == encode || encode.trim().length() < 0) {
throw new IOException("请求报文未指明请求编码");
}
byte data[] = new byte[len];
// 把buffer数组的值复制到data数组
System.arraycopy(buffer, 0, data, 0, len);
// 通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String
String inJson = new String(data, encode);
return inJson;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2.2
package com.zl.http.json;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
/**
*
* @author zenglong
*
* @Description: 采用httpclient插件的post方式发送流二进制流数据到HTTP服务端
*
*/
public class HttpClient2 {
/**
* 发送post请求,客户端采用二进制流发送,服务端采用二进制流介绍
* @param json 入参的json格式的报文
* @param url http服务器的地址
* @return 返回响应信息
*/
public static String postHttpReq(String json,String url) {
HttpClient httpClient = new HttpClient();
byte b[] = json.getBytes();//把字符串转换为二进制数据
RequestEntity requestEntity = new ByteArrayRequestEntity(b);
EntityEnclosingMethod postMethod = new PostMethod();
postMethod.setRequestEntity(requestEntity);// 设置数据
postMethod.setPath(url);// 设置服务的url
postMethod.setRequestHeader("Content-Type", "text/html;charset=GBK");// 设置请求头编码
// 设置连接超时
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(
5 * 1000);
// 设置读取超时
httpClient.getHttpConnectionManager().getParams().setSoTimeout(20 * 1000);
String responseMsg = "";
int statusCode = 0;
try {
statusCode = httpClient.executeMethod(postMethod);// 发送请求
responseMsg = postMethod.getResponseBodyAsString();// 获取返回值
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();// 释放连接
}
if (statusCode != HttpStatus.SC_OK) {
System.out.println("HTTP服务异常" + statusCode);
}
return responseMsg;
}
//POST方式发送HTTP请求
public static void main(String[] args) {
String json = "{\"客户端发送\": {\"client\": \"127.0.0.1\",\"company\": \"帕吉\"},\"Request\": {\"strBillId\": \"uuid\",\"strCcsOpId\": \"1234\"}}";
String url = "http://localhost:8080/http/httpServer2";
String outPackage = null;
outPackage = postHttpReq(json, url);
System.out.println("客户端日志----POST方式调用HTTP,请求报文为:" + json);
System.out
.println("\nauthor<pantp>===========客户端日志----POST方式调用HTTP服务,HTTP服务端响应报文如下:=============\n");
System.out.println(outPackage);
System.out
.println("\nauthor<pantp>================================================================\n");
}
}
3.启动tomcat 调用client类即可
源代码下载地址:
点击打开链接