Android - > java.net.ProtocolException:OutputStream不可用,因为已经发送了请求标头

时间:2012-08-11 09:59:13

标签: android json drupal httpurlconnection

我正在尝试从Android应用程序到php服务器 - 使用HttpUrlConnection的drupal cms网站发布数据(登录JSON格式的用户名和密码)。 这是我的代码,用于登录。 我收到了这个回复:

  

java.net.ProtocolException:OutputStream因请求而不可用   标题已经发送!

我在google&其他stackoverflow问题,但无法找到我的问题的任何解决方案。所以请帮助。

感谢收听。

   HttpURLConnection httpcon = null;
          int status = 0;

         try {
              httpcon = (HttpURLConnection) ((new URL("my URL here").openConnection()));
              httpcon.setDoOutput(true);
              httpcon.setRequestProperty("Content-Type", "application/json");
              httpcon.setRequestProperty("Accept", "application/json");
            httpcon.setRequestMethod("POST");

               status = httpcon.getResponseCode();

               httpcon.getHeaderFields();
               System.out.println("===================>httpcon.getHeaderFields()"+httpcon.getHeaderFields());


        } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


          try {
            httpcon.connect(); 
             byte[] outputBytes = "{'username':'uname','password':'pass'}".getBytes("UTF-8");

             OutputStream os = httpcon.getOutputStream();
              os.write(outputBytes);




              os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return status;

1 个答案:

答案 0 :(得分:0)

您在代码的第一部分调用httpcon.getResponseCode()httpcon.getHeaderFields()。正如HttpUrlConnection的javadoc中所提到的,这会导致执行HTTP请求。这是有道理的,因为要读取响应头字段,您需要响应,并且要获得响应,您必须发出请求。

然后执行输出流填充,由于请求已经发送,因此输出失败。

要使其工作,您需要重新排序代码,以便在访问响应内容之前设置所有请求内容。这些方面的东西:

byte[] outputBytes = "{'username':'uname','password':'pass'}".getBytes("UTF-8");
try {
    HttpURLConnection httpcon = (HttpURLConnection) ((new URL("my URL here").openConnection()));

    //prepare the request
    httpcon.setDoOutput(true);
    httpcon.setRequestProperty("Content-Type", "application/json");
    httpcon.setRequestProperty("Accept", "application/json");
    httpcon.setRequestMethod("POST");
    httpcon.connect(); // May not be needed
    OutputStream os = httpcon.getOutputStream();
    os.write(outputBytes);

    //get the response
    status = httpcon.getResponseCode();
    httpcon.getHeaderFields();
    System.out.println("===================>httpcon.getHeaderFields()"+httpcon.getHeaderFields());
} //catch block left out