欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java用 httpclient请求一般的mvc接口

程序员文章站 2022-07-13 13:54:50
...

 

java用 httpclient请求一般的mvc接口:这种不存在跨域问题,没有webservrice复杂

ajxa也可以调用mvc类型接口只不过有跨域问题,可以用拦截器处理:

 

 

工具类:

 

package com.itm.weixin.common;

 

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

 

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

 

public class HttpClient {

 

private static final Log logger = LogFactory.getLog(HttpClient.class);

 

public static String sendGet(String url, String param) throws Exception {

        String result = "";

        HttpURLConnection httpConn = null;

        BufferedReader in = null;

        try {

            String urlNameString = url + "?" + param;

            URL realUrl = new URL(urlNameString);

            // 打开和URL之间的连接

            httpConn = (HttpURLConnection) realUrl.openConnection();

            // 设置通用的请求属性

            //httpConn.setRequestProperty("accept", "*/*");

            httpConn.setRequestProperty("Accept", "application/json");

            httpConn.setRequestProperty("Accept-Charset", "UTF-8");

            httpConn.setConnectTimeout(5000); 

            httpConn.setReadTimeout(5000); 

            httpConn.setDoOutput(true);

            // 建立实际的连接

            httpConn.connect();

            int responseCode = httpConn.getResponseCode();

            if (responseCode != 200) {

            logger.error("Http request Error,responseCode=" + responseCode +", requestUrl:" + url +",requestParamsJson=" + param);

            throw new Exception("Http request Error,responseCode=" + responseCode + ", requestUrl:" + url + ",requestParamsJson=" + param); 

            } else {

            logger.info("get Success!" + "requestUrl:" + url + ", requestParamsJson:" + param);

            }

            // 定义 BufferedReader输入流来读取URL的响应

            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));

            String line;

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

                result += line;

            }

        } catch (Exception e) {

        throw e;

        } finally {

        httpConn.disconnect();

            try {

                if (in != null) {

                    in.close();

                }

            } catch (Exception e1) {

            throw e1;

            }

        }

        return result;

    }

 

}

 

 

 

 

应用:

 

reqUrl = ConfigInfo.getPropertiesValue("betweenAllowedRangeUrl");

WeixinApplyInfo weixinApplyInfo = (WeixinApplyInfo) baseService.findObject(WeixinApplyInfo.class, "orderNo", orderNoReq);

reqParam = "productType=" + saleFollowEntity.getProductCode() +"&amount=" + weixinApplyInfo.getApplyAmount();

 

 

resultJson = HttpClient.sendGet(reqUrl, reqParam);

 

JSONObject applyAmountJsonObject = JSONObject.fromObject(resultJson);

 

 

 

 

 

相关标签: httpClient