HttpUrlConnection的GET请求和POST请求

1、Get方式,该方式向服务器传递数据是直接把数据拼接在URL后面。获取数据是直接读取流。

/**
	 * Get方式请求数据
	 * @param urlStr
	 * @return
	 */
	public static String get(String urlStr) {
		HttpURLConnection conn = null;
		try {
			// 发送给服务器的参数直接拼接在URL的后面
			// http://192.168.0.110/app/index?username=XX&password=XX
			URL url = new URL(urlStr);
			// 获得HttpURLConnection对象
			conn = (HttpURLConnection) url.openConnection();
			// 设置请求方法为GET
			conn.setRequestMethod("GET");
			// 连接最长时间为10S
			conn.setConnectTimeout(10 * 1000);
			// 读取数据的时间为6S
			conn.setReadTimeout(6 * 1000);
			// 获得服务器返回的响应吗
			int responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				// 请求成功,获取输入流,读取服务器返回的字符串
				InputStream inputStream = conn.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int len = -1;
				byte[] buffer = new byte[1024];
				while ((len = inputStream.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
				}
				String result = baos.toString();
				baos.close();
				return result;
				// 如果是获取服务器返回的图片,直接使用
				// Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}

		return null;
	}



2、Post方式,向服务器传递数据是以流的方式往服务器写数据,也可以带在请求头里面。获取数据也是读取流。

/**
	 * Post方式请求数据
	 * @param urlStr
	 * @return
	 */
	public static String post(String urlStr) {
		HttpURLConnection conn = null;
		try {
			// 发送给服务器的参数不能拼接在URL后面,而是以流的方式写入
			// http://192.168.0.110/app/index
			URL url = new URL(urlStr);
			// 获得HttpURLConnection对象
			conn = (HttpURLConnection) url.openConnection();
			// 设置请求方法为POST
			conn.setRequestMethod("POST");
			// 连接最长时间为10S
			conn.setConnectTimeout(10 * 1000);
			// 读取数据的时间为6S
			conn.setReadTimeout(6 * 1000);
			// 设置为输出流,默认是不会的
			conn.setDoOutput(true);
			// 设置请求头信息
			// conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

			// 往服务器写数据
			OutputStream os = conn.getOutputStream();
			String data = "username=XX&password=XX";
			os.write(data.getBytes());
			// 获得服务器返回的响应吗
			int responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				// 请求成功,获取输入流,读取服务器返回的字符串
				InputStream inputStream = conn.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int len = -1;
				byte[] buffer = new byte[1024];
				while ((len = inputStream.read(buffer)) != -1) {
					baos.write(buffer, 0, len);
				}
				String result = baos.toString();
				baos.close();
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

3、GET和POST的区别

  • GET传送的数据量较小,不能大于2KB(这主要是因为受URL长度限制)。POST传送的数据量较大,一般被默认为不受限制。但理论上,限制取决于服务器的处理能力。
  • GET 安全性较低,POST安全性较高。因为GET在传输过程,数据被放在请求的URL中,而如今现有的很多服务器、代理服务器或者用户代理都会将请求URL记 录到日志文件中,然后放在某个地方,这样就可能会有一些隐私的信息被第三方看到。另外,用户也可以在浏览器上直接看到提交的数据,一些系统内部消息将会一 同显示在用户面前。POST的所有操作对用户来说都是不可见的。

<think>好的,我现在需要回答用户关于如何在Java中使用HttpURLConnectionGETPOST方法传递参数的问题。首先,我应该回顾用户提供的引用资料,特别是引用[1]、[2]、[3]、[4],看看里面有没有示例代码或者说明。 用户的问题是关于如何携带参数的,所以需要分别处理GETPOST两种情况。对于GET请求,参数通常是附加在URL后面的查询字符串,比如在URL末尾加上?key1=value1&key2=value2。而POST请求则需要将参数写入输出流中,可能还需要设置正确的Content-Type头,比如application/x-www-form-urlencoded。 接下来,我需要确保示例代码的正确性。例如,在GET请求中,构建带参数的URL可能需要使用URL编码,防止特殊字符导致问题。对于POST请求,需要开启输出流,并将参数写入,同时设置DoOutput为true。此外,记得设置请求方法为POST,并处理可能的异常。 还要注意用户提到的引用[3]中的工具类,可能有一些通用的方法可以借鉴,比如参数编码请求头的设置。此外,引用[4]中的链接可能提供了具体的代码示例,但用户没有给出具体内容,所以可能需要依赖已有的引用信息。 最后,需要检查代码是否符合Java标准,比如使用try-with-resources处理资源自动关闭,确保参数正确编码,以及正确设置请求头。确保回答结构清晰,分步骤说明GETPOST的实现,并提供示例代码。</think>### Java HttpURLConnection GET/POST请求参数传递方法 通过HttpURLConnection发送GETPOST请求时,携带参数的核心差异在于参数传递位置编码方式。以下是具体实现步骤: --- #### **一、GET请求参数传递** 参数通过URL查询字符串传递,使用`URLEncoder`进行编码: ```java // 构建带参数的URL String baseUrl = "https://api.example.com/data"; String param1 = URLEncoder.encode("value1", "UTF-8"); String param2 = URLEncoder.encode("特殊字符&", "UTF-8"); String urlWithParams = baseUrl + "?key1=" + param1 + "&key2=" + param2; URL url = new URL(urlWithParams); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) { String line; while ((line = in.readLine()) != null) { System.out.println(line); } } ``` > 注意:必须对每个参数值进行URL编码,否则特殊字符会导致请求失败[^2] --- #### **二、POST请求参数传递** 参数写入请求体,需设置`Content-Type`开启输出流: ```java String postUrl = "https://api.example.com/submit"; URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); // 允许写入输出流 // 设置表单格式 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String params = "username=" + URLEncoder.encode("user1", "UTF-8") + "&password=" + URLEncoder.encode("pass@123", "UTF-8"); try (OutputStream os = conn.getOutputStream()) { byte[] input = params.getBytes(StandardCharsets.UTF_8); os.write(input, 0, input.length); } // 读取响应(与GET相同) ``` > 关键点:必须同时设置`setDoOutput(true)`正确的Content-Type[^3] --- #### **三、工具类优化建议** 可封装通用方法处理参数编码: ```java public static String buildParams(Map<String, String> params) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { if (sb.length() > 0) sb.append("&"); sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")) .append("=") .append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return sb.toString(); } ``` 调用示例: ```java Map<String, String> paramMap = new HashMap<>(); paramMap.put("location", "New York"); paramMap.put("category", "IT"); String query = buildParams(paramMap); // 自动编码参数 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值