使用restTemplate访问外部接口

package com.example.demo;

import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Resource
    private RestTemplate restTemplate;

    /**
     * json数据的处理,后台发起请求
     */

    @Test
    public void contextLoads() {
        JSONObject jsobj1 = new JSONObject();
        JSONObject jsobj2 = new JSONObject();
        jsobj2.put("deviceID", "112");
        jsobj2.put("channel", "channel");
        jsobj2.put("state", "0");
        jsobj1.put("item", jsobj2);
        jsobj1.put("requestCommand", "control");
        //发起请求方法一
        //post1(jsobj1,"http://192.168.3.4:8080/HSDC/test/authentication");
        //发起请求方式二  在spring boot框架下才可以使用!创建并注入RestTemplateConfig类
        //post2(jsobj1,"http://192.168.3.4:8080/HSDC/test/authentication");

    }

    public  String post2(JSONObject json,String path) {
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        //请求体
        HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
        //发起请求,并且以字符串的形势返回,具体怎么请看我另外一篇博客。
        String jsonResult = restTemplate.postForObject(path, formEntity, String.class);
        return jsonResult;
    }

    /*public  String post1(JSONObject json,String path) {
        String result = "";
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            post.setHeader("Content-Type", "appliction/json");
            post.addHeader("Authorization", "Basic YWRtaW46");
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "appliction/json"));
            post.setEntity(s);
            HttpResponse httpResponse = client.execute(post);
            InputStream in = httpResponse.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                strber.append(line + "\n");

            }
            in.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }
        System.out.println("result==" + result);
        return result;
    }*/


}

 

package com.rf.wit_harns_service.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {
    @Bean
       public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
           return new RestTemplate(factory);
       }
    
       @Bean
       public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
           SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
           //设置请求时间
           factory.setReadTimeout(500000);//单位为ms
         //设置连接时间
           factory.setConnectTimeout(5000);//单位为ms
           return factory;
       }

}

加入我们群

如果有需要,欢迎可以加入我们的QQ群!(QQ搜索 816175200,加入我们的QQ群吧!)
有任何问题,也可以加入我们的QQ群,欢迎交(che)流(dan)!也欢迎参观我的博客www.aquestian.cn

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

答 案

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值