相对于使用HttpClient,HttpUrlConnection ,使用Spring的RestTemplate来模拟HTTP请求相对来说更方便(可以偷更多懒)
maven配置
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.3</version> <scope>test</scope> </dependency> <!--RestTemplate所需要包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.5.RELEASE</version> </dependency>
RestTemplate初始化
RestTemplate rest = new RestTemplate(); //如果不需要对Content-Type:application/json的支持 则可以去掉 FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue, SerializerFeature.QuoteFieldNames, SerializerFeature.DisableCircularReferenceDetect); fastConverter.setFastJsonConfig(fastJsonConfig); List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.parseMediaType("application/json; charset=UTF-8")); fastConverter.setSupportedMediaTypes(fastMediaTypes); rest.getMessageConverters().add(fastConverter); fastConverter.setSupportedMediaTypes(fastMediaTypes); rest.getMessageConverters().add(fastConverter);
生成请求头,可以自定义属性
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>(); headers.add("Content-Type", "application/json; charset=UTF-8"); headers.set("Accept", "application/json");
发送请求
String body="this is bodystr";//httpbody的部分 可以以json格式K-V值,post发送的属性均在这 HttpEntity<Object> entity = new HttpEntity<Object>(body, headers); String result=rest.exchange(url, HttpMethod.POST, entity, String.class).getBody();//以String格式获取返回结果