HttpClient进行接口请求

添加相关依赖

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>

GET: 当你有参数时直接进行拼接即可,无参就不需要拼接。

HttpClient发送示例

Get 有参:

可以在网址后面直接拼接,也可以使用

httpPost.setEntity(new StringEntity(String.valueOf(params), StandardCharsets.UTF_8)); //进行后面拼接内容      
  
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 参数
        StringBuffer params = new StringBuffer();
        params.append("足球");//将想要得到的内容拼接到网站后面

        // 创建Post请求
        HttpGet httpGet = new HttpGet("https://www.baidu.com/");

        // 设置ContentType
        httpGet.addHeader("content-type", "application/json;charset=utf-8");
        httpGett.addHeader("accept", "application/json");
        httpGet.addHeader(new StringEntity(String.valueOf(params), StandardCharsets.UTF_8)); //进行后面拼接内容       // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("成功");
//            String responseString = EntityUtils.toString(responseEntity);
//            JSONObject responseJson = (JSONObject) JSON.parse(responseString);
//            String id = (String) responseJson.get("id");//根据key值 id 获取其内容
            //-----------------------------------------------------------------------------------
            URI uri = httpGet.getURI();//获得网址
            System.out.println(uri);//www.baidu.com
            HttpEntity entity = httpPost.getEntity();//获得网址实体
            InputStream content = entity.getContent();//获得网址添加内容
            StringBuffer sb;
            BufferedReader br = null;
            br = new BufferedReader(new InputStreamReader(content));//进行流的转换

            sb = new StringBuffer();
            String data;
            while ((data = br.readLine()) != null) {
                sb.append(data);
            }
            System.out.println(sb);//足球
            


//
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();

                }
                if (response != null) {
                    response.close();

                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }

    }

POST无参:

HttpClient发送示例:

    /**
	 * POST---无参测试
	 *
	 * @date 2018年7月13日 下午4:18:50
	 */
	@Test
	public void doPostTestOne() {
 
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
 
		// 创建Post请求
		HttpPost httpPost = new HttpPost("http://localhost:12345/doPostControllerOne");
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
 
			System.out.println("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

POST有参(普通参数):

注:POST传递普通参数时,方式与GET一样即可,这里以直接在url后缀上参数的方式示例。

HttpClient发送示例:

接口要求传的是list 所有要进行传list,获取时也需要进行遍历转换。

  
    @Test
    public void test() throws IOException {

        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost("http://xxxxxxxxx/api2/admin/api/depart/findDepartsBydepartNames");
//        String params = "省水利厅";
        Map<String, List<String>> params = new HashMap<>();
        List<String> dwNames = new ArrayList<>();
        dwNames.add("省水利厅");
        dwNames.add("省大数据局");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("departNameList", dwNames);

        // 设置ContentType
        httpPost.addHeader("content-type", "application/json;charset=utf-8");
        httpPost.addHeader("accept", "application/json");
        httpPost.setHeader("X-Access-Token", "xxxxxxxxxxxxxxxxxx");
        httpPost.setHeader("X-Tenant-Id", "ssssssssssssss");
        httpPost.setEntity(new StringEntity(jsonObject.toString(), StandardCharsets.UTF_8));
        CloseableHttpResponse response = null;

        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            String responseString = EntityUtils.toString(responseEntity);

            JSONObject responseJson = (JSONObject) JSON.parse(responseString);

            System.out.println(responseJson);//查看返回实体数据的内容,并根据内容的k 获取对应数据
            String result = responseJson.get("result").toString();//获取其数据
            System.out.println(result);

            ObjectMapper objectMapper = new ObjectMapper();
            List list = objectMapper.readValue(result, List.class); //将得到的数据内容转换成list
            for (int i =0 ; i<=list.size();i++){
             Map<String,String> map =  (Map<String,String>)list.get(i);

                String id = map.get("id"); //获得id----------------------结果----------------------------------

                System.out.println(id);
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值