DefaultHttpClient 远程接口调用

项目实例:

HttpUtils.java

package com.jeeplus.common.config;

import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;

@SuppressWarnings("deprecation")
public class HttpUtils {
    @SuppressWarnings("resource")
    public static String doPost(String url, String param) throws Exception {
        final String CONTENT_TYPE_TEXT_JSON = "text/json";
        DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());

        // 获取外部地址
        Global.getConfig("/runyu.properties");
        String paramAPI = "";
        try {
            paramAPI = Global.getConfig("APIURL").trim();
            if (url.indexOf("util/pubEnclosureInterface") != -1) {
                paramAPI = Global.getConfig("UPLOADURL").trim();
            }
            if (url.indexOf("cms/studentClassArticleInterceptor/articleList") != -1
                    || url.indexOf("cms/studentClassArticleInterceptor/articleDetailWeb") != -1) {
                paramAPI = Global.getConfig("MOBILEURL").trim();
            }
            if (url.indexOf("oa/roomInterface") != -1) {
                paramAPI = Global.getConfig("OAURL").trim();
            }
        } catch (Exception e) {

            e.printStackTrace();
        }

        HttpPost httpPost = new HttpPost(paramAPI + url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.setHeader("Accept", "application/json");

        StringEntity se = new StringEntity(param, Charset.forName("utf-8"));
        se.setContentType(CONTENT_TYPE_TEXT_JSON);

        CloseableHttpResponse response2 = null;
        String s2 = "";
        try {
            httpPost.setEntity(se);
            response2 = client.execute(httpPost);
            HttpEntity entity2 = null;
            entity2 = response2.getEntity();
            s2 = EntityUtils.toString(entity2, "UTF-8");
            JSONObject obj = JSONObject.fromObject(s2);
            if (obj.has("content")) {
                s2 = obj.getString("content");
            } else {
                s2 = null;
            }
            // 关闭参数流
            EntityUtils.consume(entity2);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(response2 != null){
                try {
                    response2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(client != null){
                // 两者都是关闭client
                //client.getConnectionManager().shutdown();
                client.close();
            }
        }
        return s2;
    }

}

远程接口

/**
     * 远程调用根据id查询所有机构端口 officeServiceGet
     * 
     * @param id
     * @return
     */
    public static Office officeServiceGet(String id) {

        OfficeVo officeVo = new OfficeVo();
        Gson gson = new Gson();
        officeVo.setId(id);
        officeVo.setLogUserID(UserUtils.getUser().getId());
        String param = gson.toJson(officeVo);
        String httpResult = "";
        try {
            httpResult = HttpUtils.doPost("sys/officeInterface/officeServiceGet", param);
        } catch (Exception e1) {

            e1.printStackTrace();
        }
        Office result = null;
        try {
            result = gson.fromJson(httpResult, new TypeToken<Office>() {
            }.getType());
        } catch (Exception e) {
        }
        return result;
    }

另外一个项目接口

/**
     * 根据id查询所有机构
     *
     * @param userJson
     * @return
     */
    @RequestMapping(value = "officeServiceGet", method = RequestMethod.POST)
    public @ResponseBody ResultMessage officeServiceGet(@Valid @RequestBody OfficeVo officeVo) {

        String id = officeVo.getId();
        String logUserID = officeVo.getLogUserID();
        // Gson gson = new Gson();
        // Office office = gson.fromJson(officeJson, new TypeToken<Office>() {
        // }.getType());
        Office result = officeService.get(id);
        User logUser = new User();
        logUser.setId(logUserID);
        LogUtils.saveLog(Servlets.getRequest(), "根据id查询所有机构", logUser);
        return ResultMessage.successMsg("根据id查询所有机构", result);
    }

使用

Office office = HttpUtils.officeServiceGet(createUnitID);

如果是shiro框架需要在shiro.xml中开放接口controller

<bean name="shiroFilterChainDefinitions" class="java.lang.String">下加 ${adminPath}/sys/officeInterface/*=anon

-

-

相关博文:

DefaultHttpClient过时处理建议和HTTP调用后关闭流处理

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值