HttpClient请求范文示例,及注意点提示

1、需求:A项目同步B项目数据表中符合A项目的数据,并添加到A项目自己的表中

2、分析:根据此需求,可以得到的信息很明显

① 查询符合A条件的B项目表数据

② 将符合条件的数据,同步添加到A项目表中

3、确定HttpClient工具的doPost/doGet,请求头是以什么方式进行传递,比如HttpClient中是这样的:

public static String doPost(String url, String json) {
    String body = null;
    HttpEntity entity1 = null;
    @SuppressWarnings("resource")
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(json, "UTF-8");
        post.setEntity(entity);
        post.setHeader("Content-Type", "application/json;charset=utf-8");

        // logger.info("post:" + post);

        org.apache.http.HttpResponse httpresponse = httpClient
                .execute(post);

        entity1 = httpresponse.getEntity();
        body = EntityUtils.toString(entity1, "UTF-8");
        // System.out.println(body);
    } catch (Exception ex) {
        ex.printStackTrace();
        return "exception";
    } finally {
        try {
            EntityUtils.consume(entity1);
        } catch (IOException e) {
        }
        httpClient.getConnectionManager().shutdown();
    }
    return body;
}

4、由上示例,请求参数要求是json类型的参数,那么就不能以普通参数来进行传递及进行接收

5、postman模拟json参数请求该接口,通过debug调试或打印查看是否可以拿到值

HttpClient请求范文示例,及注意点提示

6、B项目代码部分(接收方)

HttpClient请求范文示例,及注意点提示

代码附上:

/**
 * 需求:接口返回渠道所有景点数据
 * @param sceid 景区id,传null,默认查询所有
 */
@ResponseBody
@RequestMapping(value = "queryAllAgentData",method = RequestMethod.POST)
public Object queryAllAgentData(@RequestBody String sceid){
    net.sf.json.JSONObject jt = net.sf.json.JSONObject.fromObject(sceid);
    Integer cid = jt.getInt("sceid");
    List<Agent> agents = null;
    try{
        agents = agentService.queryAllAgentData(cid);
    }catch (Exception e){
        e.printStackTrace();
        return renderStatusMsg(false, "500", "异常", null);
    }
    com.alibaba.fastjson.JSONObject wsResult = new JSONObject();
    wsResult.put("agents",agents);
    return wsResult;
}

7、A项目代码部分(请求方)

HttpClient请求范文示例,及注意点提示

代码附上有点长,使用的定时器:

public class TicketAgentController implements Runnable {
    // 渠道景点
    AgentService agentService;
    private final static Logger logger = LoggerFactory.getLogger(TicketAgentController.class);

    /**
     * 需求:定时启动http请求获取票务agent表数据,并同步到仰韶agent表中
     */
    public void queryAllAgentData(Integer sceid, String interfaceUrl) {
        JSONObject jt = new JSONObject();
        jt.put("sceid",sceid);
        String cid = jt.toString();
        // 请求接口获取数据
        String result = HttpClientUtil.doPost(interfaceUrl, cid);
        // 将json字符串转成json对象
        JSONObject jsonObject = JSONObject.fromObject(result);
        String agents = jsonObject.getString("agents");
        JSONArray dataArray = JSONArray.parseArray(agents);
        Agent agent = new Agent();
        // 客流数据条数
        Integer count = agentService.selectAgentCount();
        // 票务数据条数
        int size = dataArray.size();
        // 若不相同则更新
        if (count != size) {
            // 清空表后在同步
            agentService.updateAgents();
            logger.error("开始删除当日数据,编号为"+sceid+"的景区TicketAgent删除成功~");
            for (int i = 0; i < dataArray.size(); i++) {
                com.alibaba.fastjson.JSONObject dataObject = dataArray.getJSONObject(i);
                // 渠道id
                Integer agentId = dataObject.getInteger("agentId");
                // 机构账号
                String account = dataObject.getString("account");
                String passwd = dataObject.getString("passwd");
                // 景区编号
                Integer sid = dataObject.getInteger("sceid");
                String agentname = dataObject.getString("agentname");
                // 法人
                String owner = dataObject.getString("owner");
                // 联系方式
                String tele = dataObject.getString("tele");
                Long register = dataObject.getLong("register");
                // 时间
                Date date = new Date(register);
                // 所在地
                String addressid = dataObject.getString("addressid");
                // 状态
                String state = dataObject.getString("state");
                // 账期
                String deadline = dataObject.getString("deadline");
                // 机构类型
                String type = dataObject.getString("type");
                // ota标示 0代表旅行社 1代表OTA 2代表售票员
                String otaFlag = dataObject.getString("otaFlag");
                String paramModel = dataObject.getString("paramModel");
                // 所属景区
                Integer scenicspotId = dataObject.getInteger("scenicspotId");
                // 方法地址
                String noticepath = dataObject.getString("noticepath");
                // 价格日历 0 禁用 1 启用
                String pricecalendarFlag = dataObject.getString("pricecalendarFlag");
                agent.setAgentId(agentId);
                agent.setAccount(account);
                agent.setPasswd(passwd);
                agent.setSceid(sid);
                agent.setAgentname(agentname);
                agent.setOwner(owner);
                agent.setAddressid(addressid);
                agent.setTele(tele);
                agent.setRegister(date);
                agent.setState(state);
                agent.setDeadline(deadline);
                agent.setType(type);
                agent.setOtaFlag(otaFlag);
                agent.setParamModel(paramModel);
                agent.setScenicspotId(scenicspotId);
                agent.setNoticepath(noticepath);
                agent.setPricecalendarFlag(pricecalendarFlag);
                agentService.insertSelective(agent);
            }
        }
    }

    @Override
    public void run() {
        InterfaceAddressService interfaceAddressService = SpringContextUtil.getBean(InterfaceAddressService.class);
        AccountTypeService accountTypeService = SpringContextUtil.getBean(AccountTypeService.class);
        // 使用定时器,@Autowired 无法注入service对象,需要手动注入
        agentService = SpringContextUtil.getBean(AgentService.class);
        // 查询类型为6的URL地址
        String interfaceUrl = interfaceAddressService.selectInterfaceUrl(7, 6);
        // 请求发送,并将景区id和url地址传过去
        queryAllAgentData(7, interfaceUrl);
    }
}

8、接下来将result结果转成JSONObject对象(net.sf.json.JSONObject  jt = net.sf.json.JSONObject.fromObject(result)),拿到对应的字段值然后插入A项目表中即可

上一篇:Java解析json数组三种情况


下一篇:Android——JSONObject解析JSON数据