关闭

后台发送http请求 类

73人阅读 评论(0) 收藏 举报
分类:
<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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:817次
    • 积分:46
    • 等级:
    • 排名:千里之外
    • 原创:4篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档