HttpClient 带参数get请求

背景:

本例中使用HttpClient Get请求下载存储系统中的文件。根据存储系统提供的接口文档需要传入参数。

实例1(使用字符串直接拼接get请求中的参数)
1.参数:

filename:存储系统上存储的唯一文件名。(文件名一般是文件上传时生成一个唯一的文件夹路径,这个路径保存在数据库中,要下载文件时,数据库中取出文件夹路径名,去存储系统上下载)

2.返回值

输入流,以流的形式返回,不需要保存在本地浪费资源,使用时调用方法传参拿到返回值就可以使用

eg:

public static InputStream doGet(String filename) {
   //创建HttpClient实例
    CloseableHttpClient httpClient = HttpClients.createDefault();
    StringBuffer stringBuffer = new StringBuffer();
    //拼接get请求URL(url一般包含接口需要的用户名,密码,文件名等参数)
    String url = stringBuffer.append(EmailGradeTask.EMAILGRADETASKDOWNLOADURL).append(filename).toString();

    InputStream inputStream = null;
    try {
    //创建get方法连接实例,在get方法中传入待连接地址
        HttpGet httpGet = new HttpGet(url);
        //发起请求,并返回请求响应
        HttpResponse httpResponse = httpClient.execute(httpGet);
        //得到响应实体
        HttpEntity entity = httpResponse.getEntity();
        //得到实体中文件
        inputStream = entity.getContent();
        long length = entity.getContentLength();
        if (length <= 0) {
            System.out.println("下载文件不存在!");
            return inputStream;
        }
        System.out.println("The response value of token:" + httpResponse.getFirstHeader("token"));

    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
//            try {
//                if (inputStream != null) {
//                    inputStream.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
        return inputStream;
    }
实例二(有的get请求直接拼接请求参数访问不到资源,需要用到URI包封装参数)

在这里插入图片描述

public static String httpClientBySina() throws Exception{
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 定义请求的参数
		URI uri = new URIBuilder("https://hq.sinajs.cn/").setParameter("rn", "1563526094204").setParameter("list",  "USDCNY").build();
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(uri);
		//response 对象
		CloseableHttpResponse response = null;
		String resultString="0";
		try {
			// 执行http get请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
		//		System.out.println("内容长度:" + resultString);
			} else {
				throw new Exception("新浪接口获取汇率失败!");
			}
		} finally {
			if (response != null) {
				response.close();
			}
			httpclient.close();
		}
		return resultString;
	}
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值