【Java】【29】post,get通用方法加强

前言:

前一篇:

【Java】【20】后台发送GET/POST方法 - 花生喂龙 - 博客园
https://www.cnblogs.com/huashengweilong/p/10909507.html

正文:

1,请求的接口,需要POST过去大量参数,且需要接收返回值。(如果只有两三个参数,直接拼接就行了,例如:"param1=A&param2=B")

private Logger logger = LoggerFactory.getLogger(this.getClass());

//请求外部接口
public void requestExternalApi(UserInfo info) {
    logger.info("requestExternalApi begin, info:" + info.toString()); //建议打日志
    String userId = ""; //想要得到的值
    String API_URL = "http://test.com/createXX"; //建议写在配置文件里
    String jsonStr = JSONObject.fromObject(info).toString(); //转为json格式,这样就不用拼接多个参数了
    JSONObject jsonObject = HttpUtil.httpRequest(API_URL, "POST", "param=" + jsonStr); //发起请求,param是自己定的一个参数名

    if (jsonObject == null) {
        logger.info("fail, jsonObject is null");
    } else {
        logger.info("jsonObject:" + jsonObject.toString());
        if (jsonObject.containsKey("userId")) {
            userId = jsonObject.getString("userId");
        }
    }
    return userId;
}

2,另一个项目中被访问的接口(如果只有两三个参数,直接接收就行了,例如:createXX(String param1, String param2))

@ApiOperation(value = "对外接口")
@ApiImplicitParams({
        @ApiImplicitParam(name = "param", value = "json格式字符串([{\"touser\":\"A,B\",\"first\":\"123\"...}])", required = true, dataType = "String", paramType = "query")
})
@RequestMapping(value = "createXX", method = RequestMethod.POST)
public void createXX(String param) {
    JSONObject jsonObject = JSONObject.fromObject(param);
    UserInfo info = (UserInfo) JSONObject.toBean(jsonObject, UserInfo.class);
    this.xxService.createXX(info);
}

3,HttpUtil.httpRequest方法

package com.common.utils;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

public final class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class.getName());

    //post,get通用方法
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)
    {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url= new URL(requestUrl);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            //设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            //当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                //注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            //将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();

            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.info("httpRequest: Weixin server connection timed out.");
        } catch (Exception e) {
            logger.info("httpRequest: error:{}" + e);
        }
        return jsonObject;
    }
}

 

posted @ 2019-06-15 17:21  花生喂龙  阅读(322)  评论(0编辑  收藏  举报