zoukankan      html  css  js  c++  java
  • java http post/get 服务端和客户端实现json传输


    注:本文来源于《java http post/get 服务端和客户端实现json传输


    最近需要写http post接口所以学习下。

    总的还是不难直接上源码!

    PostHttpClient.java 客户端
    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;
    
    
    /**
     * ********************************************************
     *  采用httpclient插件的post方式发送流二进制流数据到HTTP服务端
     **********************************************************
     * ---@author [zt_zoro1272@163.com    ]
     **********************************************************
     * ---@version
     **********************************************************
     * ---@since 2014-8-28
     */
    public class PostHttpClient {
    
    
        /**
         * ********************************************************
         * ---功能描述:         发送post请求,客户端采用二进制流发送,服务端采用二进制流介绍
         **********************************************************
         * ---@param json    入参的json格式的报文
         * ---@param url     http服务器的地址
         * ---@return       返回响应信息
         **********************************************************
         * ---@author  [zt_zoro1272@163.com    ]
         **********************************************************
         * ---@since 2014-8-28
         **********************************************************
         * ---@update:[变更日期YYYY-MM-DD][更改人姓名][变更描述]
         **********************************************************
         *
         */
        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 = "{"PubInfo": {"clinet": "10.70.128.132","company": "月月鸟0820"},"Request": {"strBillId": "18221075148","strCcsOpId": "1234"}}";
            String url = "http://localhost:8080/httl_online/postHttpServer";
            String outPackage = null;
            outPackage = postHttpReq(json, url);
            System.out.println("客户端日志----POST方式调用HTTP,请求报文为:" + json);
            System.out
                    .println("
    author<pantp>===========客户端日志----POST方式调用HTTP服务,HTTP服务端响应报文如下:=============
    ");
    
            System.out.println(outPackage);
    
            System.out
                    .println("
    author<pantp>================================================================
    ");
        }
    
    }


    PostHttpServer.java 服务端
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.security.Principal;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.HashMap;
    import java.util.Locale;
    import java.util.Map;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.ServletInputStream;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    
    /**
     * ********************************************************
     * 模拟的一个Http服务,处理客户端的post请求
     **********************************************************
     * ---@author [zt_zoro1272@163.com    ]
     **********************************************************
     * ---@version
     **********************************************************
     * ---@since 2014-8-28
     */
    public class PostHttpServer extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        /*
         * 代码逻辑分以下三部分:
         * 1.获得请求报文
         * 2.根据请求报文的信息去做业务逻辑,然后封装返回报文
         * 3.输出相应报文
         */
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            String inJson = null;// 保存HTTP客户端请求报文
            String outJson = null;// 保存HTTP服务端输出报文
    
            // 获得输人报文然后打印出来
            inJson = getInJson(request);
            System.out
                    .println("
    author<pantp>===========服务端日志----POST方式接收HTTP请求,HTTP服务端收到的请求报文如下:==========
    ");
            System.out.println(inJson);
            System.out
                    .println("
    author<pantp>=================================================================
    ");
    
            // 以下代码部分获得请求报文,然后去做校验,转换以及其他的调用其他的业务逻辑等,这里就不管它
            // ........................................................................
    
            // 下面部分是输出部分的处理
            outJson = "{"Response": {"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;
        }
    
        // 不提供get的处理方式
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
             String inJson = null;// 保存HTTP客户端请求报文
             String outJson = null;// 保存HTTP服务端输出报文
    
             // 获得输人报文然后打印出来
             inJson = getInJson(request);
             System.out
                     .println("
    author<pantp>===========服务端日志----POST方式接收HTTP请求,HTTP服务端收到的请求报文如下:==========
    ");
             System.out.println(inJson);
             System.out
                     .println("
    author<pantp>=================================================================
    ");
    
             // 以下代码部分获得请求报文,然后去做校验,转换以及其他的调用其他的业务逻辑等,这里就不管它
             // ........................................................................
    
             // 下面部分是输出部分的处理
             outJson = "{"Response": {"code": "0","message": "成功","data": "12345"}}";// 输出不部分也以JSON格式的字符串输出,这里我就写死
    
             response.setContentType("application/json; charset=UTF-8");
             response.getWriter().print(outJson);
        }
    
    
    }
    web.xml配置
    <!-- 模拟HTTP的调用,写的一个只处理POST请求的http服务 -->
        <servlet>
            <servlet-name>PostHttpServer</servlet-name>
            <servlet-class>com.sitechasia.xinnet.online.util.cloudhttp.PostHttpServer</servlet-class>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>PostHttpServer</servlet-name>
            <url-pattern>/postHttpServer</url-pattern>
        </servlet-mapping>
  • 相关阅读:
    Button
    启动活动最佳写法
    随时随地退出程序
    知晓当前是在哪个活动
    Failed to resolve:com.android.support:appcompat-v7:报错处理
    未能从程序集“System.ServiceModel”中加载类型“System.ServiceModel.Activation.HttpModule”
    office文档图标不正常显示
    feign和ribbon的异常捕捉
    rocketMQ为什么会重复消费
    springboot时区问题
  • 原文地址:https://www.cnblogs.com/ios9/p/10526660.html
Copyright © 2011-2022 走看看