【发布时间】:2012-09-29 02:09:32
【问题描述】:
我从 API lvl 4 开始使用此代码,它一直有效,直到 ICS。 由于 API 级别 14,当我使用 https URL 时,此代码块始终执行 GET 方法而不是 POST。如果我使用 http URL,代码会执行 POST 并且一切正常。 自 lvl14 以来我得到的异常是 FileNotFoundException。我完全不明白发生了什么。请帮忙。谢谢。
private byte[] Post(byte[] Header, byte[] Body, String protocol) throws IOException, MyAppConnectionException
{
HttpURLConnection urlConnection = null;
byte[] responseData = null;
try
{
String url = MyApp.getContext().getResources().getString(R.string.ServerEndPoint);
URL u = new URL(url);
urlConnection = (HttpURLConnection) u.openConnection();
urlConnection.setConnectTimeout(15000);
urlConnection.setReadTimeout(45000);
urlConnection.setRequestProperty("CONTENT-TYPE", protocol);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.connect();
}
catch(IOException ioex)
{
throw new MyAppConnectionException();
}
if(urlConnection != null)
{
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
int msgLength = (int)(4 + Header.length + Body.length);
outputStream.write(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(msgLength).array());
outputStream.write(Header);
outputStream.write(Body);
outputStream.flush();
outputStream.close();
if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
DataInputStream inputStream = new DataInputStream(urlConnection.getInputStream());
int dataLength = inputStream.available();
byte[] msgbLength = new byte[4];
inputStream.read(msgbLength, 0, 4);
int length = ByteBuffer.wrap(msgbLength).order(ByteOrder.LITTLE_ENDIAN).getInt();
assert(dataLength == length);
responseData = new byte[length - 4];
inputStream.readFully(responseData, 0, length - 4);
inputStream.close();
}
urlConnection.disconnect();
}
return responseData;}
【问题讨论】:
-
关于 POST 和 GET 的地方发生了变化,但是如果你这样做
urlConnection.setDoOutput(true);它总是会在以前是 GET 的地方执行 POST -
问题是,如果我使用 http URL,它实际上会执行 POST,如果它的 https setdooutput(true) 什么都不做并且方法是 GET...
-
如果加
urlConnection.setRequestMethod("POST");? -
试过了,尝试初始化一个 HttpsURLConnection 对象而不是 HttpURLConnection,它总是做 GET 方法。
-
试试
Content-Type而不是CONTENT-TYPE。
标签: android post android-4.0-ice-cream-sandwich httpurlconnection