如何将音频上传到服务器:Blackberry

时间:2013-01-21 08:01:34

标签: audio blackberry java-me upload

我正在尝试将.amr文件上传到服务器。我的代码如下:

private static void uploadRecording(byte[] data) {
    byte[] response=null;
    String currentFile = getFileName();  //the .amr file to upload
    StringBuffer connectionStr=new StringBuffer("http://www.myserver/bb/upload.php");
    connectionStr.append(getString());
    PostFile req;
    try {
        req = new PostFile(connectionStr.toString(),
           "uploadedfile", currentFile, "audio/AMR", data    );
        response = req.send(data);
    } catch (Exception e) {
        System.out.println("====Exception: "+e.getMessage());
    }
    System.out.println("Server Response : "+new String(response));
}

public class PostFile
{
    static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
    byte[] postBytes = null;
    String url = null;

    public PostFile(String url, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
    {    
        this.url = url;
        String boundary = getBoundaryString();
        String boundaryMessage = getBoundaryMessage(boundary, fileField, fileName, fileType);
        String endBoundary = "\r\n--" + boundary + "--\r\n";
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bos.write(boundaryMessage.getBytes());
        bos.write(fileBytes);
        bos.write(endBoundary.getBytes());
        this.postBytes = bos.toByteArray();
        bos.close();
    }

    String getBoundaryString()
    {
        return BOUNDARY;
    }

    String getBoundaryMessage(String boundary, String fileField, String fileName, String fileType)
    {
        StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
        res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
           .append("Content-Type: ").append(fileType).append("\r\n\r\n");
        return res.toString();
    }

    public byte[] send(byte[] fileBytes) throws Exception
    {
        HttpConnection hc = null;
        InputStream is = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] res = null;
        try
        {    
            hc = (HttpConnection) Connector.open(url);
            hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
            hc.setRequestMethod(HttpConnection.POST);
            hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
               "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH ,Integer.toString(fileBytes.length));
            OutputStream dout = hc.openOutputStream();
            dout.write(postBytes);
            dout.close();
            int ch;

            is = hc.openInputStream();  // <<< EXCEPTION HERE!!!

            if(hc.getResponseCode()== HttpConnection.HTTP_OK)
            {
                while ((ch = is.read()) != -1)
                {
                    bos.write(ch);
                }
                res = bos.toByteArray();
                System.out.println("res loaded..");
            }
            else {
                System.out.println("Unexpected response code: " + hc.getResponseCode());
                hc.close();
                return null;
            }
        }
        catch(IOException e)
        {
            System.out.println("====IOException : "+e.getMessage());
        }
        catch(Exception e1)
        {
            e1.printStackTrace();
            System.out.println("====Exception : "+e1.getMessage());
        }
        finally
        {
            try
            {
                if(bos != null)
                   bos.close();
                if(is != null)
                   is.close();
                if(hc != null)
                   hc.close();
            }
            catch(Exception e2)
            {
                System.out.println("====Exception : "+e2.getMessage());
            }
        }
        return res;
    }
}

上面突出显示的是抛出异常的代码行:未连接。 有人可以告诉我可以做些什么来纠正这个问题?非常感谢。

更新:

public static String getString()
{
 String connectionString = null;       
 String uid = null;
// Wifi
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
        connectionString = ";interface=wifi";
}
else
{
 ServiceBook sb = ServiceBook.getSB();
 net.rim.device.api.servicebook.ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
 for (int i = 0; i < records.length; i++) {
     if (records[i].isValid() && !records[i].isDisabled()) {
         if (records[i].getUid() != null &&
        records[i].getUid().length() != 0) {
             if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&                       
                     (records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
                     (records[i].getUid().toLowerCase().indexOf("mms") == -1) ) {
                        uid = records[i].getUid();
                        break;
             }
         }
     }
 }
 if (uid != null)
 {
     connectionString = ";deviceside=true;ConnectionUID="+uid;
 }
 else
 {                       
     // the carrier network
     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                  
                 System.out.println("No Uid");

                connectionString = ";deviceside=true";
            } else {
                // otherwise, use the Uid to construct a valid carrier
                // BIBS
                // request                  
                 System.out.println("uid is: " + carrierUid);
                connectionString = ";deviceside=false;connectionUID="
                        + carrierUid + ";ConnectionType=mds-public";
            }
     } 

     //(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 bugging
    // the user unnecessarily.       
    else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {          
        System.out.println("There is no available connection.");
    }

    // In theory, all bases are covered so this shouldn't be
    // reachable.
    else {          
        System.out.println("no other options found, assuming device.");
        connectionString = ";deviceside=true";
    }
 }
}
 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 static String getCarrierBIBSUid() {
    try {
        net.rim.device.api.servicebook.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();
                }
            }
        }
    } catch (Exception e) {         
        System.out.println("====Exception : "+e.toString());
    }
    return null;
}

0 个答案:

没有答案