1

我正在尝试将 json 字符串从我的 BlackBerry OS < 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());
}

该代码以我不完全理解的方式工作。上述代码的作者建议使用httpURL服务器的 URL + 我的 json 字符串。最终结果是,在我的服务器上,不是到达 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;
}
4

1 回答 1

7

第一行应该只是您的 URL

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 及更高版本一起使用,这是完整的类。如果你想用 < 4.5 编译它,你可能需要用它的值 1 替换常量 COVERAGE_DIRECT。

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) {
        }
    }
}
于 2013-04-23T17:41:24.570 回答