Java-BlackBerry上的HTTP发布请求

我正在尝试从BlackBerry OS<发送json字符串. 7.X应用程序到我的服务器.我正在尝试使用HTTP Post请求.到目前为止,我所做的是:

String httpURL = "http://ip_of_my_server/phpServer/receiver2.php/" + jsonString;

try {
    HttpConnection httpConn;
    httpConn = (HttpConnection) Connector.open(httpURL + getConnectionString());
    httpConn.setRequestMethod(HttpConnection.POST);
    httpConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
    byte[] request_body = httpURL.getBytes();
    for (int i = 0; i < request_body.length; i++) {
        _outStream.writeByte(request_body[i]);
    }
    DataInputStream _inputStream = new DataInputStream(httpConn.openInputStream());
    StringBuffer _responseMessage = new StringBuffer();
    int ch;
    while ((ch = _inputStream.read()) != -1) {
        _responseMessage.append((char) ch);
    }
    String res = (_responseMessage.toString());
    String response = res.trim();
    System.out.println("!!!!!!!!!!!!!! Response is: " + response);
    httpConn.close();
} catch (Exception e) {
    Dialog.alert("Error - " + e.toString());
}

该代码以我不完全理解的方式工作.上面代码的作者建议将我的json字符串服务器的URL用作httpURL.最终结果是,在我的服务器上,而不是到达json字符串,而是到达了这样的字符串:

http://ip_of_my_server/phpServer/receiver2.php/ + jsonString

我对Java不熟悉.我以前已经针对WP7和iOS做到了这一点,并在httpUrl中放置了服务器URL,然后使用命令将json字符串“追加”到http请求中,并且一切正常.

我如何将json字符串附加到上述HttpRequest,而不是将其添加到URL,以便在服务器中仅到达JSON字符串?

编辑(提供使用的其余代码)

//used to specify connection type ( wifi - 3g - etc )
public static String getConnectionString() {
    String connectionString = null;
    // Wifi is the preferred transmission method
    if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
        connectionString = ";interface=wifi";
    }
    // Is the carrier network the only way to connect?
    else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
        String carrierUid = getCarrierBIBSUid();
        if (carrierUid == null) {
            // Has carrier coverage, but not BIBS. So use the carrier's TCP network
            connectionString = ";deviceside=true";
        } else {
            // otherwise, use the Uid to construct a valid carrier BIBS request
            connectionString = ";deviceside=false;connectionUID="+carrierUid + ";ConnectionType=mds-public";
        }
    }
    // Check for an MDS connection instead (BlackBerry Enterprise Server)
    else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
        connectionString = ";deviceside=false";
    }
    // If there is no connection available abort to avoid hassling the user unnecessarily
    else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
        connectionString = "none";
    }
    // In theory, all bases are covered by now so this shouldn't be reachable.But hey, just in case ...
    else {
        connectionString = ";deviceside=true";
    }
    System.out.println("!!!!!!!!!!!!!! Connection type is: " + connectionString);
    return connectionString;
    }

/**
 * Looks through the phone's service book for a carrier provided BIBS
 * network
 * 
 * @return The uid used to connect to that network.
 */
private synchronized static String getCarrierBIBSUid() {
    ServiceRecord[] records = ServiceBook.getSB().getRecords();
    int currentRecord;

    for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
        if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
            if (records[currentRecord].getName().toLowerCase()
                    .indexOf("bibs") >= 0) {
                return records[currentRecord].getUid();
            }
        }
    }

    return null;
}
最佳答案
第一行应该只是您的网址

String httpURL = "http://ip_of_my_server/phpServer/receiver2.php";

而且,您仅应根据请求将json字符串发送到服务器.

而不是byte [] request_body = httpURL.getBytes();

使用byte [] request_body = jsonString.getBytes();

这是OS 5.0及更高版本的方法

public static HttpConnection getHttpConnection(String url, byte[] postData) {
    HttpConnection conn = null;
    OutputStream out = null;
    try {
        conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
        if (conn != null) {
            if (postData == null) {
                conn.setRequestMethod(HttpConnection.GET);
                conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            } else {
                conn.setRequestMethod(HttpConnection.POST);
                conn.setRequestProperty("Content-Length", String.valueOf(postData.length));
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");

                out = conn.openOutputStream();
                out.write(postData);
                out.flush();
            }
            if (conn.getResponseCode() != 0) {
                return conn;
            }
        }
    } catch (Exception e) {
    } finally {
        try {
            out.close();
        } catch (Exception e2) {
        }
    }

    //Only if exception occurs, we close the connection.
    //Otherwise the caller should close the connection himself.
    try {
        conn.close();
    } catch (Exception e1) {
    }
    return null;
}

如果您希望它可用于OS 4.2及更高版本,则这里是完整的类.如果要使用<进行编译,则可能需要用其值1替换常量COVERAGE_DIRECT. 4.5.

public class ConnectionHelper {
    /**
     * Returns the working connection type. The connection types can be BIS, BES, TCP, WAP2, TCPIP
     */
    public static HttpConnection getHttpConnection(String url, byte[] postData) {
        int[] preferredOrder = new int[] { CONNECTION_WIFI, CONNECTION_BIS, CONNECTION_BES, CONNECTION_UNITE, CONNECTION_WAP2, CONNECTION_TCPIP, };

        for (int i = 0; i < preferredOrder.length; i++) {
            int type = preferredOrder[i];
            if (isPresent(type)) {
                HttpConnection conn = null;
                OutputStream out = null;
                try {
                    conn = (HttpConnection) Connector.open(convertURL(type, url));
                    if (conn != null) {
                        if (postData == null) {
                            conn.setRequestMethod(HttpConnection.GET);
                            conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
                        } else {
                            conn.setRequestMethod(HttpConnection.POST);
                            conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postData.length));
                            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                            conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");

                            out = conn.openOutputStream();
                            out.write(postData);
                            out.flush();
                        }
                        if (conn.getResponseCode() != 0) {
                            return conn;
                        }
                    }
                } catch (Exception e) {
                } finally {
                    try {
                        out.close();
                    } catch (Exception e2) {
                    }
                }
            }
        }
        // Only if exception occurs, we close the connection.
        // Otherwise the caller should close the connection himself.
        try {
            conn.close();
        } catch (Exception e1) {
        }

        return null;
    }

    /** Stores transport ServiceBooks if found. Otherwise, null */
    private static ServiceRecord srMDS, srWiFi, srBIS, srWAP2, srUnite;

    private static final int CONNECTION_DEFAULT = 0;
    private static final int CONNECTION_BIS = 1;
    private static final int CONNECTION_BES = 2;
    private static final int CONNECTION_TCPIP = 3;
    private static final int CONNECTION_WIFI = 4;
    private static final int CONNECTION_WAP2 = 5;
    private static final int CONNECTION_UNITE = 6;

    private static final int CONFIG_TYPE_BES = 1;

    private static final String UNITE_NAME = "Unite";

    private static void checkTransportAvailability() {
        initializeTransportAvailability();
    }

    /**
     * Initializes the ServiceRecord instances for each transport (if available). Otherwise leaves it null. Also determines if sufficient coverage is available for each transport
     * and sets coverage* flags.
     */
    private static void initializeTransportAvailability() {
        ServiceBook sb = ServiceBook.getSB();
        ServiceRecord[] records = sb.getRecords();

        for (int i = 0; i < records.length; i++) {
            ServiceRecord myRecord = records[i];
            String cid, uid;

            if (myRecord.isValid() && !myRecord.isDisabled()) {
                cid = myRecord.getCid().toLowerCase();
                uid = myRecord.getUid().toLowerCase();

                // BIS
                if (cid.indexOf("ippp") != -1 && uid.indexOf("gpmds") != -1) {
                    srBIS = myRecord;
                }

                // BES
                if (cid.indexOf("ippp") != -1 && uid.indexOf("gpmds") == -1) {
                    srMDS = myRecord;
                }
                // WiFi
                if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") != -1) {
                    srWiFi = myRecord;
                }

                // Wap2.0
                if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1 && uid.indexOf("mms") == -1) {
                    srWAP2 = myRecord;
                }

                // Unite
                if (getConfigType(myRecord) == CONFIG_TYPE_BES && myRecord.getName().equals(UNITE_NAME)) {
                    srUnite = myRecord;
                }
            }
        }
    }

    /**
     * Gets the config type of a ServiceRecord using getDataInt below
     * 
     * @param record
     *            A ServiceRecord
     * @return configType of the ServiceRecord
     */
    private static int getConfigType(ServiceRecord record) {
        return getDataInt(record, 12);
    }

    /**
     * Gets the config type of a ServiceRecord. Passing 12 as type returns the configType.
     * 
     * @param record
     *            A ServiceRecord
     * @param type
     *            dataType
     * @return configType
     */
    private static int getDataInt(ServiceRecord record, int type) {
        DataBuffer buffer = null;
        buffer = getDataBuffer(record, type);

        if (buffer != null) {
            try {
                return ConverterUtilities.readInt(buffer);
            } catch (EOFException e) {
                return -1;
            }
        }
        return -1;
    }

    /**
     * Utility Method for getDataInt()
     */
    private static DataBuffer getDataBuffer(ServiceRecord record, int type) {
        byte[] data = record.getApplicationData();
        if (data != null) {
            DataBuffer buffer = new DataBuffer(data, 0, data.length, true);
            try {
                buffer.readByte();
            } catch (EOFException e1) {
                return null;
            }
            if (ConverterUtilities.findType(buffer, type)) {
                return buffer;
            }
        }
        return null;
    }

    private static String convertURL(int connectionType, String url) {
        switch (connectionType) {
        case CONNECTION_BES:
            url += ";deviceside=false";
            break;
        case CONNECTION_BIS:
            url += ";deviceside=false" + ";ConnectionType=mds-public";
            break;
        case CONNECTION_TCPIP:
            url += ";deviceside=true";
            break;
        case CONNECTION_WIFI:
            url += ";interface=wifi";
            break;
        case CONNECTION_WAP2:
            url += ";deviceside=true;ConnectionUID=" + srWAP2.getUid();
            break;
        case CONNECTION_UNITE:
            url += ";deviceside=false;ConnectionUID=" + srUnite.getUid();
            break;
        }

        return url;
    }

    private static boolean isPresent(int connectionType) {
        checkTransportAvailability();

        switch (connectionType) {
        case CONNECTION_BIS:
            return (srBIS != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B));

        case CONNECTION_BES:
            return (srMDS != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS));

        case CONNECTION_WIFI:
            return (srWiFi != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT, RadioInfo.WAF_WLAN, false));

        case CONNECTION_TCPIP:
            return (CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT));

        case CONNECTION_WAP2:
            return (srWAP2 != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT));

        case CONNECTION_UNITE:
            return (srUnite != null && CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS));

        case CONNECTION_DEFAULT:
            return true;
        }

        return false;
    }
}

最后发布您的数据.

public void sendJson(String jsonString) {
    String httpURL = "http://ip_of_my_server/phpServer/receiver2.php";
    HttpConnection httpConn = null;

    try {
        httpConn = getHttpConnection(httpURL, jsonString.getBytes());

        if(httpConn.getResponseCode() == 200) {
            //If you need the output, then read it. Otherwise comment it.
            byte[] data = IOUtilities.streamToBytes(httpConn.openInputStream());
            String response = new String(data);
            System.out.println("!!!!!!!!!!!!!! Response is: " + response);
        }
    } catch (Exception e) {
    }
    finally {
        try {
            httpConn.close();
        } catch (Exception e2) {
        }
    }
}

转载注明原文:Java-BlackBerry上的HTTP发布请求 - 代码日志