HttpURLconnection使用get有参请求

1、在pom.xml中添加依赖包

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.46</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.9</version>
		</dependency>

2、创建测试类(HttpURLconnectionTest2.java)

package com.jeff;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeff.entity.SysUser;

public class HttpURLconnectionTest2 {

	public static void main(String[] args) {

		try {
			URL url = new URL("http://localhost:8080/getUser?id=1");
			// 得到connection对象。
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			// 设置网络连接超时时间
			connection.setConnectTimeout(3000);
			// 设置请求方式
			connection.setRequestMethod("GET");
			// 连接
			connection.connect();
			// 得到响应码
			int responseCode = connection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				// 得到响应流
				InputStream inputStream = connection.getInputStream();
				// 将响应流转换成字符串
				String jsonStr = inputStreamToString(inputStream);
				if (StringUtils.isNotBlank(jsonStr)) {
					JSONObject jsonObject = JSON.parseObject(jsonStr);
					JSONObject job = jsonObject.getJSONObject("result");
					if (job != null) {
						SysUser user = JSONObject.toJavaObject(job, SysUser.class);
						System.out.println(user.toString());
					}
				}
			}

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

	/**
	 * 
	 * @description: 将输入流转换成字符串
	 * @author: Jeff
	 * @date: 2019年12月15日
	 * @param inputStream 输入流
	 * @return
	 */
	private static String inputStreamToString(InputStream inputStream) {
		StringBuffer buffer = new StringBuffer();
		InputStreamReader inputStreamReader;
		try {
			inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

}

3、控制台输出结果
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值