后台发送http请求 类

<span style="white-space:pre">		</span>public static String readPostContent(String httpUrl, String content, String charSetName) {
			StringBuilder sb = new StringBuilder();
			BufferedReader reader = null;
			try {
				URL resourceUrl = new URL(httpUrl);
				HttpURLConnection connection = (HttpURLConnection) resourceUrl.openConnection();
		
				// 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true
				connection.setDoOutput(true);
				// Read from the connection. Default is true.
				connection.setDoInput(true);
				// Set the post method. Default is GET
				connection.setRequestMethod("POST");
				// Post 请求不能使用缓存
				connection.setUseCaches(false);
				// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
				connection.setInstanceFollowRedirects(true);
				// 表明urlencoded编码过的form参数
				connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset="+charSetName);
				// 开始连接(连接前配置必须要完成,否则无效)
				connection.connect();
				PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),charSetName));  
				out.println(content);
				out.flush();
				out.close(); // flush and close
//				reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			    reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charSetName));

				String line;
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				connection.disconnect();
			} catch (MalformedURLException e) {
				System.out.println("http请求时,URL(" + httpUrl + ")格式错误: "+ e);
				e.printStackTrace();
			} catch (ProtocolException e) {
				System.out.println("http请求时,协议异常: "+ e);
				e.printStackTrace();
			} catch (IOException e) {
				System.out.println("http请求时,IO异常: "+ e);
				e.printStackTrace();
			} finally {
				if (null != reader)
					try {
						reader.close();
					} catch (IOException e) {
					}
			}
		
			return sb.toString();
		}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值