HttpURLConnection Cannot write output after reading input.

是因为 , 我在 用了 int 管道之后, 又 用了 out 管道, 所以报错了, 没测试。。。 又坑了。

public static String sendPostRequest(String path,String param) throws IOException {
		String sendUrlString=path+param;
		
		URL url = new URL(sendUrlString);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//设置post方式请求
		conn.setRequestMethod("POST");
		//将超时控制在 8S 内,因为没有 引入 多线程发送。为了防止RTX 那边有问题,延迟太久了,对用户体验不太好。
		// 一般 反应是很快的,所以不考虑 使用线程池了。没必要搞复杂。
		conn.setReadTimeout(3000); // 读取  超时 3秒 。
		conn.setConnectTimeout(5000);//连接超时 5秒 。
		
		//conn.setRequestProperty("Accept-Charset", "utf-8");
		//conn.setRequestProperty("contentType", "utf-8");
		conn.setRequestProperty("Content-type", "application/x-java-serialized-object");
		
		
		//设置传入参数,post 
		conn.setDoOutput(true); 
		conn.connect(); // 主动建立间接 。,默认也是会建立的。
		
		//传入参数
		//conn.getOutputStream().write(param.toString().getBytes());
		// 解决中文乱码, 在 Linux 下没有乱码,本地有 ,估计 Linux 已经 帮我们转码了一次了。
		// 而且 Linux 下 的默认编码并没有 和 本地的一致,比如tomcat的啊, 系统的啊,没有 该为 默认中文的等。
		// 既然这样 在 Linux 下没有 乱码,可以不用管,如果以后  可以 去 修改 服务器里面的 编码。
		//BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		
		// 解决中文乱码,在 Linux 下有乱码,本地没有
		//BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"GBK"));
		
		// out 管道 必须放在 int 管道之前 使用的。这个是 HRRt 规定的
		//可以不主动关闭, 默认会自动关闭的。特别是 随着 int 管道关闭同时关闭的。
		conn.getOutputStream().flush(); // 这个最好有
		 conn.getOutputStream().close();  // 关闭代码可以不用。
		
		InputStreamReader isreader = new InputStreamReader(conn.getInputStream());
		BufferedReader reader = 
				new BufferedReader(isreader);
		
		String readingString= "";
		// 读取完所有内容
		String readl=null;
		while (( readl=reader.readLine() )!=null) {
			
			readingString=readingString+readl;
			
			readl=null;
		}
		
		// 必须放在 int 管道之前 使用的。, 不要放在 这里,会报错:  Cannot write output after reading input.
		//conn.getOutputStream().close(); 
		
		// 养成 关闭 管道的习惯 。
		conn.getInputStream().close();
		isreader.close();
		reader.close();
		
		return readingString;
		
	}

参考地址: http://www.blogjava.net/supercrsky/articles/247449.html

参考地址: http://blog.csdn.net/u010278162/article/details/51054664

转载于:https://my.oschina.net/ouminzy/blog/848143

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值