HttpClent 后台调用API接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35002313/article/details/85039474

参考文章

https://blog.csdn.net/illbehere/article/details/72851045

1. 引入依赖

                        <dependency>
                        <groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		 	<version>4.3.5</version>
		        </dependency>

2. 服务接口

   @RequestMapping(value = "/index")
    @ResponseBody
    public String index(String id){
        if(id.equals("a")){
            return  id;
        }else
        System.out.print("index请求");
        return  "ok";
    }

3. HttpClent使用post传参

 @RequestMapping(value = "/get")
    @ResponseBody
    public String get(String id) throws Exception {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("id", id));
        HttpClient httpClient = HttpClients.createDefault();
        String url = "http://127.0.0.1:8082/index";
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse res = httpClient.execute(httpPost);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(res.getEntity());// 返回json格式:
            return result;
        }
        return null;
    }

4. localhost:8080/get->localhost:8081/index

猜你喜欢

转载自blog.csdn.net/qq_35002313/article/details/85039474