java实现get类型接口调用

GET:

		(一)GET通常用于获取服务端数据。
		常见发起GET请求的方式有:URL 、src/href、表单(form)。
		(二)GET方式提交数据的格式:
		格式:index.php?userName=jack&password=123 (注意:index.php?key=value&key=value。 userName=jack&password=123 叫做查询字符串)
		参数名与参数值之间没有空格
		参数值不需要使用单双引号包括
		(三)GET方式提交数据特点:
		1、get方式在url后面拼接参数,只能以文本的形式传递参数。
		2、传递的数据量小,4kb左右(不同浏览器会有差异)。
		3、安全性低,会将信息显示在地址栏。
		4、速度快,通常用于对安全性要求不高的请求

(四)用java实现简单的get请求。

/**
	 * 无参数的get请求
	 * 
	 * @param uri 接口地址
	 */
	public static String doGet(String uri) {
		try {
//		 * 1、创建request连接.
			HttpGet get = new HttpGet(uri);
			// 设置请求头
			get.setHeader(Constants.HEADER_MEDIA_TYPE_NAME, Constants.HEADER_MEDIA_TYPE_VALUE);
			// 创建一个客户端
			HttpClient client = HttpClients.createDefault();
			// 发送请求,并接受响应
			HttpResponse response = client.execute(get);
			// 获取接口响应封装到一个方法中,方便调用,返回body
			return getResult(response);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 带参数的get请求,参数为map
	 * 
	 * @param uri 接口地址
	 * @param map 接口参数
	 */
	public static String doGet(String uri, Map<String, String> mapParams) {
		try {
			// 在uri上拼接参数2.那么一个完整的url地址,基本格式如下:
			// https://host:port/path?xxx=aaa&ooo=bbb
			Set<String> keySet = mapParams.keySet();
			int i = 0;
			for (String key : keySet) {
				if (i == 0) {
					uri = uri + "?" + key + "=" + mapParams.get(key);
				} else {
					uri = uri + "&" + key + "=" + mapParams.get(key);
				}
				i++;
			}
			// 创建一个get请求
			HttpGet get = new HttpGet(uri);
			// 设置请求头
			get.addHeader(Constants.HEADER_MEDIA_TYPE_NAME, Constants.HEADER_MEDIA_TYPE_VALUE);
			get.addHeader(Constants.CONTENT_TYPE, Constants.CONTENT_TYPE_FORM);
			// 创建一个客户端
			HttpClient client = HttpClients.createDefault();
			// 客户端发送请求,接受响应
			HttpResponse response = client.execute(get);
			return getResult(response);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 获取响应结果
	 * 
	 * @param response
	 * @return
	 * @throws IOException
	 */
	public static String getResult(HttpResponse response) throws IOException {
		// 获取状态码
		int code = response.getStatusLine().getStatusCode();
		System.out.println(code);
		// 获取body
		HttpEntity entity = response.getEntity();
		String body = EntityUtils.toString(entity);
		System.out.println(body);
		// 获取头信息
		Header[] allHeaders = response.getAllHeaders();
		String headers = Arrays.toString(allHeaders);
		System.out.println(headers);

		// 返回body
		return body;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值