2012-05-18 5 views
2

j2me httpconnection을 사용하여 서버에 wav 파일을 업로드하려고합니다. 그러나 나는 그것을 할 수 없다. 그것은 서버에 바이트를 쓸 때 널 포인터 예외를 던집니다.J2ME를 사용하여 wav 파일 업로드

샘플은 다음과 같습니다.

os.write(postBytes); 라인에서 예외가 발생합니다. 아무 생각없이? 그리고 내가 업로드하는 파일은 test.pcm입니다. 서버에 파일을 전송하는 데 사용

public String send() throws Exception 
{ 

    form.append("Inside Send()"); 

    bos = new ByteArrayOutputStream(); 

try 
    { 
     form.append("Making connections"); 
     hc = (HttpConnection) Connector.open(url, Connector.READ_WRITE); 
     form.append("length: " + postBytes.length + ""); 
     hc.setRequestProperty("Content-Length", "100573"); 
     hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString()); 
     hc.setRequestMethod(HttpConnection.POST); 
     //Content-Length: 27 
     os = hc.openOutputStream(); 
     form.append("Writing bytes to Server" + postBytes); 

     try { 
      os.write(postBytes); 
      os.flush(); 

      form.append("Uploading done and closing output connection"); 

      form.append("Waiting for response"); 
      int ch; 
      is = hc.openInputStream(); 
      while ((ch = is.read()) != -1) 
      { 
       bos.write(ch); 
      } 
      form.append("Response wrote to byte array"); 
      //res = bos.toByteArray(); 
      res = bos.toString(); 
     } 
     catch(Exception e) { 
      form.append("Exception during write: " + e.getMessage()); 
     } 
    } 
    catch(Exception e) 
    { 
     form.append("Expcetion caught1: " + e.getMessage()); 
     //e.printStackTrace(); 
    } 
    finally 
    { 
     try 
     { 
      if(bos != null) 
       bos.close(); 
      if(is != null) 
       is.close(); 
    if(hc != null) 
       hc.close(); 
     } 
     catch(Exception e2) 
     { 
      form.append("Expcetion caught2: " + e2.getMessage()); 
     } 
    } 
    return res; 
} 
+0

는 postBytes –

+1

을 인스턴스화하는 코드를 추가 할 수 있습니다 내가 발견 전화의 그것의 문제. 어쨌든 내 코드는 노키아에서 작동했습니다. 내 휴대 전화가 큰 파일을 업로드 할 수없는 것 같아요. 파일을 작은 조각으로 나누고 업로드해야합니다. –

답변

1

내 클래스 :

/* 
* REVISION HISTORY: 
* 
* Date   Author(s) 
* CR   Headline 
* ============================================================================= 
* 05/05/2010 Douglas Daniel Del Frari 
* Initial version to Send the Animation Poke to server site. 
* ============================================================================= 
* 17/05/2010 Douglas Daniel Del Frari 
* Adding a tip documentation in this class. 
* ============================================================================= 
* 27/05/2010 Douglas Daniel Del Frari 
* Enhancement to try/catch error throw at send method 
* ======================================================================================== 
*/ 

import java.io.ByteArrayOutputStream; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.util.Enumeration; 
import java.util.Hashtable; 

import javax.microedition.io.Connector; 
import javax.microedition.io.HttpConnection; 

/** 
* This class encapsulated the Send process of Data to Server Site, 
* using the HTTP protocol. 
* 
* <p>Example of use: <br><br> 
* 
* Hashtable params = new Hashtable(); 
* params.put("gesture", "1:3,1:3,1:3,1:-3,1:-3,1:-3"); 
* params.put("message", "Ola simone... pessoal! viva o GREMIO!"); 
* params.put("sound", "teste.mp3"); // option field 
* params.put("texture", "textura.bmp"); 
* String URL = MIDletController.getInstance().getAppProperty(HttpRequest.SERVER_URL_PROPERTY_KEY); 
* HttpRequest req = new HttpRequest(URL, params); 
* byte[] response = req.send(); 
*/ 
public class HttpRequest { 

    static final String BOUNDARY = "-------BUSINESS-here---V2ymHFg03ehbqgZCaKO6jy"; 

    public static final String SERVER_URL_PROPERTY_KEY = "ServerURL"; 

    byte[] postBytes = null; 
    String url = null; 

    /** 
    * This constructor create an object used aim to a file transfer. 
    * 
    * @param url 
    *   the URL of server 
    * @param params 
    *   one or more parameters encapsulated on Hashtable object 
    * @param fileField 
    *   argument to identify of this field 
    * @param fileName 
    *   the name of file with extension (e.g. audio/amr) 
    * @param fileType 
    *   the mime type know 
    * @param fileBytes 
    *   the byte array 
    * 
    * @throws Exception 
    */ 
    public HttpRequest(String url, Hashtable params, String fileField, 
      String fileName, String fileType, byte[] fileBytes) 
      throws Exception { 
     this.url = url; 

     String boundary = getBoundaryString(); 
     String boundaryMessage = getBoundaryMessage(boundary, params, 
       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(); 
    } 

    /** 
    * 
    * This constructor create an object used aim to a file transfer. 
    * 
    * @param url 
    *   the URL of server 
    * @param params 
    *   one or more parameters encapsulated on Hashtable object 
    * 
    * @throws Exception 
    *    some problem. 
    */ 
    public HttpRequest(String url, Hashtable params) throws Exception { 
     this.url = url; 

     String boundary = getBoundaryString(); 
     String boundaryMessage = getBoundaryMessage(boundary, params); 
     String endBoundary = "\r\n--" + boundary + "--\r\n"; 

     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     bos.write(boundaryMessage.getBytes()); 
     bos.write(endBoundary.getBytes()); 

     this.postBytes = bos.toByteArray(); 
     bos.close(); 
    } 

    /** 
    * get the Boundary string 
    * @return 
    */ 
    private String getBoundaryString() { 
     return BOUNDARY; 
    } 

    /** 
    * 
    * @param boundary 
    * @param params 
    * @param fileField 
    * @param fileName 
    * @param fileType 
    * @return 
    */ 
    private String getBoundaryMessage(String boundary, Hashtable params, 
      String fileField, String fileName, String fileType) { 
     StringBuffer res = new StringBuffer("--").append(boundary).append(
       "\r\n"); 

     Enumeration keys = params.keys(); 

     while (keys.hasMoreElements()) { 
      String key = (String) keys.nextElement(); 
      String value = (String) params.get(key); 

      res.append("Content-Disposition: form-data; name=\"").append(key) 
        .append("\"\r\n").append("\r\n").append(value).append(
          "\r\n").append("--").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(); 
    } 

    /** 
    * 
    * @param boundary 
    * @param params 
    * @return 
    */ 
    private String getBoundaryMessage(String boundary, Hashtable params) { 
     StringBuffer res = new StringBuffer("--").append(boundary).append(
       "\r\n"); 

     Enumeration keys = params.keys(); 

     while (keys.hasMoreElements()) { 
      String key = (String) keys.nextElement(); 
      String value = (String) params.get(key); 

      res.append("Content-Disposition: form-data; name=\"").append(key) 
        .append("\"\r\n").append("\r\n").append(value).append(
          "\r\n").append("--").append(boundary) 
        .append("\r\n"); 
     } 

     return res.toString(); 
    } 

    /** 
    * Send the data to the URL of Server Site using the POST connection. 
    * 
    * @return the response of server. 
    * @throws Exception 
    */ 
    public byte[] send() 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); 



      OutputStream dout = hc.openOutputStream(); 

      dout.write(postBytes); 
      if (dout!=null) { 
       dout.close(); 
       dout = null; 
      } 

      int ch; 
      is = hc.openInputStream(); 

      while ((ch = is.read()) != -1) { 
       bos.write(ch); 
      } 
      res = bos.toByteArray(); 
     } catch (Exception e) { 
      // if an error occurred connecting to the server. 
      throw new Exception(e.getMessage()); 

     } finally { 
      try { 
       if (bos != null) 
        bos.close(); 

       if (is != null) 
        is.close(); 

       if (hc != null) 
        hc.close(); 
      } catch (Exception e2) { 
       e2.printStackTrace(); 
      } 
     } 
     return res; 
    } 


} 
+0

파일 크기가 10MB 미만인 경우 어떻게 할 것입니까? – CAMOBAP

+0

매우 큰 파일을 테스트 한 적이 없습니다. 그러나받는 서버쪽에는 최대 크기 (~ 10MB) 파일에 대한 설정이 있어야합니다. –

관련 문제