远程调用post请求和get请求


   /**
     * 获取用户
     */
    @RequestMapping("getUserMassages")
    public Map<String,Object> getuserMassge(String SAPDB){
        Map<String,Object> map=new HashMap<>();
        //获取用户 
        String userMassge=HttpUtil.doGets("http://api.xxxx.com.cn/user/userxxxxxx?xxx="+xxx);
        List<Map<String,Object>> UserStock = JSONObject.parseObject(userMassge, List.class);
        map.put("userMassge",UserStock);
        return map;
    }
private static String token = "";
private static Date createDate = new Date();

public static String getToken(){
if("".equals(token)){
return getUrlToken();
}
else{
Date now = new Date();
if(now.getTime() - createDate.getTime() > 7000000l ){
return getUrlToken();
}
}
return token;
}

public static String getUrlToken(){
String tokenStr = HttpUtil.doGet("http://xxxx.xxxxx.com.cn/user/xxx?xxx=xxx&xxxx=123456&xxxx=2","");
HttpResult result = JSONObject.parseObject(tokenStr,HttpResult.class);
if("success".equals(result.getStatus())){
Token t = JSONObject.parseObject(result.getResult(), Token.class);
token=t.getToken();
}
return token;
}

package org.springblade.desk.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * create by Dell on 2020/6/17
 */
public class HttpUtil {
    // get请求
    public static String doGet(String httpurl,String token) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            URL url = new URL(httpurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            if(!StringUtils.isEmpty(token)){
                connection.setRequestProperty("token", token);
            }
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            connection.connect();
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("
");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }
        return result;
    }

    // post请求参数为json格式
    public static String doPostByJson(String url, String json) throws Exception {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            StringEntity requestEntity = new StringEntity(json, "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
            result = httpClient.execute(httpPost, responseHandler);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        return result;
    }

    // get请求
    public static String doGets(String httpurl) {
        System.out.println("进入get远程请求======================httpurl============="+httpurl);
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            URL url = new URL(httpurl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            connection.connect();
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("
");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }
        return result;
    }
}
原文地址:https://www.cnblogs.com/xianz666/p/13180167.html