Spring---RestTemplate远程调用python rest接口

浪子不回头ぞ 提交于 2020-01-19 07:16:13

Spring---RestTemplate远程调用python rest接口


近期公司做一个项目,Java这边直接远程调用Python远程提供的接口。我这边是自己搭建的SpringCloud 后端的框架,具体不说,因为俩者之间的通信是靠Spring
提供的Rest,和框架之间并无任何一点影响。Python那边我使用的是Flask模块提供请求和响应。如果有人疑问,可以找我,我必然知无不言言无不尽得。我写这东西也是为了记住他。对于一个陌生的领域,网上收到的东西,比较杂乱,我也是通过半天吧,才把一些东西弄懂,拼凑出来,对于不懂得人,确实太难了。希望这篇文章可以帮到你,解决实际得问题。好了,废话不多说,下面开始了。

首先配置RestTemplate,Rest的配置一成不变的,自己在网上找一下都是一样的

package com.example.demo.utils;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
 
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
 
 
@Component
public class RestTemplateConfig {

    @Bean
    @ConditionalOnMissingBean({RestOperations.class, RestTemplate.class})
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);

        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
        while (iterator.hasNext()) {
            HttpMessageConverter<?> converter = iterator.next();
            if (converter instanceof StringHttpMessageConverter) {
                iterator.remove();
            }
        }

        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }

    @Bean
    @ConditionalOnMissingBean({ClientHttpRequestFactory.class})
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(15000);
        factory.setConnectTimeout(12000);
        return factory;
    }

}

这里传值用的是fastjson JSON格式,引入Jar包

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.62</version>
		</dependency>

我们这里是远程调用rest,post方法需要带参数 首先设置请求头

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);

传递参数

JSONObject info = new JSONObject();
info.put("filePath","123");

因为我用的是SpringCloud的原因,具体的IP与端口在其他服务上,就暂时不管

请求和响应

HttpEntity<String> entity = new HttpEntity<>(info.toString() , httpHeaders);
HttpEntity<String> response = restTemplate.postForEntity(url, entity , String.class);

Java这边具体代码

  @GetMapping("/-user")
    public String PythonUser() {
//        Map<String,String> info = new HashMap<String, String>();
//        info.put("filePath", "121");
        JSONObject info = new JSONObject();
        info.put("filePath","123");
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        String url = "http://py-sidecar/getUser";
        HttpEntity<String> entity = new HttpEntity<>(info.toString() , httpHeaders);
        HttpEntity<String> response = restTemplate.postForEntity(url, entity , String.class);
        //JSONObject json = restTemplate.postForEntity(url, info, JSONObject.class).getBody();
//       return restTemplate.getForEntity("http://py-sidecar/getUser", String.class).getBody();
        return response.toString();
    }

具体的地址你不用和我一样,根据自己情况编写就行

下面是Python这边环境

import json
from flask import Flask, Response, request

app = Flask(__name__)


@app.route("/health")
def health():
    result = {'status': 'UP'}
    return Response(json.dumps(result), mimetype='application/json')


@app.route("/getUser", methods=["POST"])
def getUser():
    if request.method == 'POST':
        print("post")
        print(request.data)
    elif request.method == "GET":
        print("GET")
    result = {'username': 'python', 'password': 'python'}
    return Response(json.dumps(result), mimetype='application/json')


app.run(port=3000, host='0.0.0.0')

这样就可以获取java那边传过来的参数

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!