HttpClent 后台调用API接口

参考文章

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

 

1. 引入依赖

                        
                        org.apache.httpcomponents
			httpclient
		 	4.3.5
		        

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 nvps = new ArrayList();
        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

你可能感兴趣的:(java)