get/post方式调用http接口

15410年前 (2015-11-13)java技术3350

 1. 项目环境如下:

myeclipse8.5 、tomcat5.0/weblogic、xp、JDK:开发1.5,编译1.4

为了方便,在原来的web项目UpDown中新建了一个httpcall包,用来保存http接口和调用的客户端。

image.png

 

 

 

2.准备需要的jar包

* commons-httpclient-3.0.jar
* commons-logging.jar
* commons-codec-1.3.jar

 

3.class&method

HttpClient

GetMethod

PostMethod

 

start

接口写了一个servlet来接收客户端get/post的请求

web.xml需要加入以下配置:

< !-- 模拟HTTP的调用,写的一个http接口 -->
   <servlet>
       <servlet-name>TestHTTPServer</servlet-name>
       <servlet-class>httpcall.TestHTTPServer</servlet-class>
   </servlet>
   <servlet-mapping>
       <servlet-name>TestHTTPServer</servlet-name>
       <url-pattern>/httpServer</url-pattern>
   </servlet-mapping>

 

TestHTTPServer.java的代码如下:

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 TestHTTPServer  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 {
        this.doGet(request, response);
    }
}




HttpClientUtil.java的代码如下:

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;


public class HttpClientUtil {
    
    private static final Log log = LogFactory
    .getLog(HttpClientUtil.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+"&param2="+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/UpDown/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));
    }
}


本文原创,转载必追究版权。

分享给朋友:

相关文章

plsql 中number类型字段 取消科学计数法显示

 PL/SQL DEVELOPER中禁用科学计数法:Tools - Prefrence - SQL Window - 选择:"Number fields to_char&quo...

org.tigris.subversion.javahl.ClientException:Attempted to lock an already-locked dir

 svn更新或提交时候报错:org.tigris.subversion.javahl.ClientException:Attempted to lock an already-locke...

base64加密java算法

base64加密java算法

 一、Base64算法概述Base64算法最早应用于解决电子邮件传输的问题。它是一种基于64个字符的编码算法,根据RFC 2045的定义:“Base64内容传输编码是一种以任意8位字节序列组...

freemarker 判断日期变量为空处理 及InvalidReferenceException异常处理

at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:98);InvalidR...

MyEclipse 10安装svn

MyEclipse 10安装svn

 方法一:在线安装(推荐)1.打开HELP->MyEclipse ConfigurationCenter。切换到SoftWare标签页。 2.点击Add Site 打开对话框...

MyEclipse10.7注册码生成

注意经验里的工具可能不可用,请点击 生成注册码工具  下载。提取码:p1w4MyEclipse10.7注册码激活步骤:点击下面的链接http://jingyan.baidu.com/arti...

评论列表

点我收录您
10年前 (2015-11-16)

我只会用asp php实现这个

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。