我正在尝试使用 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;