HTTPClient 发送请求

客户端发送代码

/**
     * 用httpPost发送
     * 
     * @param url
     * @param json
     * @throws Exception
     */
    public static String httpPostWithJSON(String url, String json) {
        try {
            // 将JSON进行UTF-8编码,以便传输中文
            String encoderJson = URLEncoder.encode(json, "UTF-8");

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/text");

            StringEntity se = new StringEntity(encoderJson);
            se.setContentType("Content-Type");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/text"));

            httpPost.setEntity(se);

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();

            return buffer.toString();
        } catch (IOException e) {

            e.printStackTrace();

        }
        return null;
    }

servlet接收端代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        String reqBody = sb.toString();
        String reqStr = URLDecoder.decode(reqBody, "utf-8");
        JSONObject obj = JSONObject.fromObject(reqStr);
        HashMap<String, Object> map = (HashMap<String, Object>) JSONObject.toBean(obj, HashMap.class);
        Object jsonMsg =  map.get("jsonMsg");
        JSONArray objList = JSONArray.fromObject(jsonMsg);
        String headerType = (String) map.get("headerType");
        System.out.println("headerType:" + headerType.toString());
        System.out.println("jsonMsg:" + objList);
        response.setContentType("text/html;charset=utf-8");
        RPCClient rpc = null;
        String result = null;
        try {
            rpc = new RPCClient();
            result = rpc.call(headerType, objList.toString());
        } catch (Exception e1) {
            e1.printStackTrace();
            result = "{flag:'false'}";//不然客户端有问题会自动退出
            if(rpc != null){
                rpc.close();
            }
        }

        logger.info(" 获取返回值'" + result + "'");

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
            response.getWriter().print(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

struts 方式

public static String getHttpResult(String urlStr, String content) {

        URL url = null;

        HttpURLConnection connection = null;

        try {

            url = new URL(urlStr);

            connection = (HttpURLConnection) url.openConnection();

            connection.setDoOutput(true);

            connection.setDoInput(true);

            connection.setRequestMethod("POST");

            connection.setUseCaches(false);

            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.connect();

            DataOutputStream out = new DataOutputStream(connection.getOutputStream());

            out.write(content.getBytes("utf-8"));

            out.flush();

            out.close();

            BufferedReader reader =

                    new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));

            StringBuffer buffer = new StringBuffer();

            String line = "";

            while ((line = reader.readLine()) != null) {

                buffer.append(line);

            }

            reader.close();

            return buffer.toString();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            if (connection != null) {

                connection.disconnect();

            }

        }

        return null;

    }

接收端代码就不贴了直接在action里面定义你的参数就OK

下载地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值