1

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

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;
4

1 回答 1

0

您在代码的第一部分调用httpcon.getResponseCode()and 。httpcon.getHeaderFields()正如 javadoc 中提到的HttpUrlConnection,这会导致 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
于 2012-08-11T11:06:37.213 回答