使用HttpURLConnection和https地址的Android ICS无法做post方法

时间:2012-04-22 20:52:13

标签: android post android-4.0-ice-cream-sandwich httpurlconnection

我正在使用此代码,因为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;}

1 个答案:

答案 0 :(得分:1)