HttpClent background call API interface

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_35002313/article/details/85039474

Reference article

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

 

1. dependence introduction

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

2. Service Interface

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

3. HttpClent use post mass participation

 @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

Guess you like

Origin blog.csdn.net/qq_35002313/article/details/85039474