我想实现在同一个URL和HttpURLConnection连接中仅改变参数串的值(即“?”后的值),可是在实际测试时确出现下述的错误。好像是同一个HttpConnection对象(即下面的“uc”)在执行了getInputStream()方法后,在执行getOutputStream()方法时就会出错。希望各位能帮我解决。
附部分代码//定义为全局静态变量
public static URL url = null;
public static HttpURLConnection uc = null;
//初始化
public init() {
    if (url == null && uc == null){
      try {
        url = new URL("http://localhost/test.asp?");
        uc = (HttpURLConnection)url.openConnection();
        uc.setDoOutput(true);
        uc.setDoInput(true);      }
      catch (MalformedURLException ex) {
      }
      catch (IOException ex1) {
      }
    }  }
//拼好参数串传给下面的函数
private String send(String strUrl){
    try {
      PrintStream vOut = new PrintStream(uc.getOutputStream());      //(注:第一次执行上述语句时没有错误,但第二次执行时出现如下错误
        java.net.ProtocolException: Cannot write output after reading input.)      vOut.print(strUrl);
      vOut.flush();
      vOut.close();
      
      BufferedReader read = new BufferedReader(new InputStreamReader(uc.getInputStream(), "GBK"));
      int ch;
      StringBuffer buffer = new StringBuffer();
      while ( (ch = read.read()) != -1) {
        buffer.append( (char) ch);
      }
      String ret = buffer.toString();
      
      read.close();
      
      return ret;    }catch (MalformedURLException e1) {
      e1.printStackTrace();
    }
    catch (IOException e2) {
      e2.printStackTrace();
    }
  }

解决方案 »

  1.   

    楼主这种做法是不正确的
    必须在URL对象构造的时候就拼好参数
    楼主的想法是取得输出流,然后输出参数串,但事实上,URL和参数串并不是已顺序的方式提交的,HTTP协议中Get方法获取页面时的参数是URL的一部分。你在获取输入流的时候才会发送完整的HTTP请求
      

  2.   

    这是一个HTTP请求示例,楼主看了就明白了
    GET /test/test.jsp?id=1&name=tom HTTP/1.1
    Accept: image/gif, image/jpeg,*/*
    Accept-Language:zh-cn
    Accept-Encoding:gzip, 
    deflateUser-Agent:Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)Host:localhost:9999
    Connection: Keep-Alive
      

  3.   

    顶。必须要完整的http请求才可以。
      

  4.   

    【领先数码商城】移动硬盘专卖店:http://shop33473501.taobao.com/
      

  5.   

    问题已经解决了!
    不过还是要特别感谢polarman(北极人)给了我重要的提示信息。
    顶者有分