java对接第三方接口的三种方式

本文详细介绍了在日常开发中使用Java进行HTTP请求时,HttpURLConnection、ApacheHttpClient、Spring的RestTemplate以及HutoolHttpUtil等工具的调用方法,重点讲解了POST请求和JSON格式数据的处理。
摘要由CSDN通过智能技术生成

在日常工作中,经常需要跟第三方系统对接,我们做为客户端,调用他们的接口进行业务处理,常用的几种调用方式有:
1.原生的Java.net.HttpURLConnection(jdk);

2.再次封装的HttpClient、CloseableHttpClient(Apache);

3.Spring提供的RestTemplate;

当然还有其他工具类进行封装的接口,比如hutool的HttpUtil工具类,里面除了post、get请求外,还有下载文件的方法downloadFile等。

HttpURLConnection调用方法

HTTP正文的内容是通过OutputStream流写入,向流中写入的数据不会立即发送到网络,而是存在于内存缓冲区中,待流关闭时,根据写入的内容生成HTTP正文。
调用getInputStream()方法时,会返回一个输入流,用于从中读取服务器对于HTTP请求的返回报文

@Slf4j
public class HttpURLConnectionUtil {
   /**
     *
     * Description: 发送http请求发送post和json格式
     * @param url      	请求URL
     * @param params    json格式的请求参数
     */
    public static String doPost(String url, String params) throws Exception {

        OutputStreamWriter out = null;
        BufferedReader reader = null;
        StringBuffer response = new StringBuffer();
        URL httpUrl = null; // HTTP URL类 用这个类来创建连接
        try {
            // 创建URL
            httpUrl = new URL(url);
            log.info("--------发起Http Post 请求 ------------- url:" + url + "---------params:" + params);

            // 建立连接
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            //设置请求的方法为"POST",默认是GET
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);// 设置不要缓存
            conn.setInstanceFollowRedirects(true);
            //由于URLConnection在默认的情况下不允许输出,所以在请求输出流之前必须调用setDoOutput(true)
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入
            conn.setDoInput(true);
            //设置超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.connect();
            // POST请求
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(params);
            out.flush();
            // 读取响应
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String lines;
            while ((lines = reader.readLine()) != null) {
                response.append(lines);
            }
            reader.close();
            // 断开连接
            conn.disconnect();
        } catch (Exception e) {
            log.error("--------发起Http Post 请求 异常 {}-------------", e);
            throw new Exception(e);
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                log.error(String.valueOf(ex));
            }
        }
        return response.toString();
    }
}

CloseableHttpClient调用

CloseableHttpClient 是一个抽象类,实现了httpClient接口,也实现了java.io.Closeable;
支持连接池管理,可复用已建立的连接 PoolingHttpClientConnectionManager
通过 httpClient.close() 自动管理连接释放
支持HTTPS访问 HttpHost proxy = new HttpHost(“127.0.0.1”, 8080, “http”);

@Slf4j
public class CloseableHttpClientUtil {
	/**
	*url 第三方接口地址
	*json 传入的报文体,可以是dto对象,string、json等
	*header 额外传入的请求头参数
	*/	
  public static String doPost(String url, Object json,Map<String,String> header) {

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost httpPost= new HttpPost(url);//post请求类型
        String result="";//返回结果
        String requestJson="";//发送报文体
        try {
        	requestJson=JSONObject.toJSONString(json);
            log.info("发送地址:"+url+"发送报文:"+requestJson);
            //StringEntity s = new StringEntity(requestJson, Charset.forName("UTF-8"));
            StringEntity s= new StringEntity(requestJson, "UTF-8");
       		// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
       		httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            httpPost.setEntity(s);
            if(header!=null){
                Set<String> strings = header.keySet();
                for(String str:strings){
                    httpPost.setHeader(str,header.get(str));
                }
            }
            HttpResponse res = httpclient.execute(httpPost);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    result = EntityUtils.toString(res.getEntity());
                    //也可以把返回的报文转成json类型
                    // JSONObject  response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        finally {
     		//此处可以加入记录日志的方法
            // 关闭连接,释放资源
           if (httpclient!= null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }
        return result;
    }
}

RestTemplate调用

//可以在项目启动类中添加RestTemplate 的bean,后续就可以在代码中@Autowired引入。
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}

@Slf4j
@Component
public class RestTemplateUtils {
	@Autowired
	private RestTemplate restTemplate;

	/**
	 * get 请求 参数在url后面  http://xxxx?aa=xxx&page=0&size=10";
	 * @param urls 
	 * @return string
	 */
	public String doGetRequest(String urls) {
		
		URI uri = UriComponentsBuilder.fromUriString(urls).build().toUri();
		log.info("请求接口:{}", urls);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> httpEntity = new HttpEntity<>(headers);
		//通用的方法exchange,这个方法需要你在调用的时候去指定请求类型,可以是get,post,也能是其它类型的请求
		ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.GET, httpEntity, String.class);
		if (responseEntity == null) {
			return null;
		}
        log.info("返回报文:{}", JSON.toJSONString(responseEntity));
		
		return responseEntity.getBody();
	}
	
	/**
	 * post 请求 参数在 request里;
	 * @param url, request
	 * @return string
	 */
	public String doPostRequest(String url, Object request){
		URI uri = UriComponentsBuilder.fromUriString(url).build().toUri();

		String requestStr= JSONObject.toJSONString(request);
		log.info("请求接口:{}, 请求报文:{}", url, requestStr);
		HttpHeaders headers = new HttpHeaders();	
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> httpEntity = new HttpEntity<>(requestStr, headers);
		ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, String.class);
				
		if (responseEntity == null) {
			return null;
		}
		
		String seqResult = "";
		try {
			if(responseEntity.getBody() != null ) {		
				if(responseEntity.getBody().contains("9001")) {
					seqResult = new String(responseEntity.getBody().getBytes("ISO8859-1"),"utf-8");
				}else {
					seqResult = new String(responseEntity.getBody().getBytes(),"utf-8");	
				}											
			}
			
			log.info("返回报文:{}", seqResult);
			
		} catch (UnsupportedEncodingException e) {
			log.error("接口返回异常", e);
		}

		return seqResult;
	}
}
  • 30
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值