最近公司项目使用了Python作CMS系统,但是数据分析和一些基础数据提供等需要用到Java来做,所以就是一个后台项目分成Java和Python来做,有一些数据就需要从Python端查出来再提供给Java使用,Python使用的是django,Java是Springboot,Python调Java可以使用Telnet调用Java的dubbo接口(会另写一篇),Java调用Python就是用Spring提供的RestTemplate
首先配置RestTemplate
package com.hqjl.career.config;
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;
/**
* @author chunying
*/
@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;
}
}
这基本是死的 不多说了 主要说下使用
我们这里是远程调用rest,post方法需要带参数
首先设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
参数
JSONObject param = new JSONObject();
param.put("gradeID",gradeID);
param.put("schoolID" , schoolID);
param.put("type" , 1);
定义URL,这里我有部分URL是在配置文件中的,不同环境ip,port可能会变动
@Value("${pythonserv}")
private String pyURL;
String URL = pyURL + "/intention/commonList";
请求以及响应接收
HttpEntity<String> entity = new HttpEntity<>(param.toString() , httpHeaders);
HttpEntity<String> response = restTemplate.exchange(URL, HttpMethod.POST , entity , String.class);
简单说一下Python端,因为有几个坑,首先Python端接收到参数解析完类型是unicode,我们取参数肯定想用的是字典类型嘛,
所以我简单写一下,有兴趣的童鞋可以试一下每一步打印type()
def commonList(request):
dict = json.loads(request.body.decode()) unicode
dict = dict.encode('utf-8') str
dict = json.loads(dict) dict