2013-06-11 55 views
1

我需要發送一個POST JSON的身體到黑莓java OS6 +的REST服務。我看過一些例子,但不知道如何創建這樣一個機構。那麼,我需要發送在POST之前創建的機構? 我需要發送的身體的一個例子是這樣的:發送正文在黑莓java OS6 +的郵件json +

身體:

{ 
    "name" : "my name", 
    "password" : "asdf", 
    "email" : "[email protected]", 
    "gender" : 0, 
} 

,該服務將返回:

{ 
    "response": { 
    "status": "ok" 
    } 
} 
+0

檢查下面的文章 – alishaik786

+0

爲請求創建一個JSON對象,使用請求的JSON對象的toString()方法返回的數據。 – Rupak

回答

1

這是解決

只需要改變字符串JSONObject的身體。

Solamente tenia que cambiar el cuerpo String JSONObject。

String url = "http://example.json"; 
String result; 
String tipoConexion = Autenticacion.getConnectionString(); 
public Consumo4() 
{   
    try{ 

     JSONObject json = new JSONObject ( 
       "{"+ 
        "'name' : 'test',"+ 
        "'email' : '[email protected]',"+ 
        "'password' : 'password',"+      
        "'gender' : 0,"+       
       "}" 
       ); 
     HttpConnection connection = (HttpConnection)Connector.open(url+tipoConexion); 
     connection.setRequestMethod(HttpConnection.POST); 

     connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); 
     connection.setRequestProperty("Accept", "application/json"); 
     connection.setRequestProperty("Content-Length", Integer.toString(json.length())); 


     System.out.println("JSON A ENVIAR --> " + json); 
     String size = "" + json.length(); 

     OutputStream os = connection.openOutputStream(); 
     os.write(json.toString().getBytes("UTF-8")); 

     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     InputStream responseData = connection.openInputStream(); 
     byte[] buffer = new byte[20000]; 
     int bytesRead = responseData.read(buffer); 
     while(bytesRead > 0) { 
      baos.write(buffer, 0, bytesRead); 
      bytesRead = responseData.read(buffer); 
     } 
     baos.close(); 
     connection.close(); 

     result = new String(baos.toByteArray(), "UTF-8"); 
     System.out.println("JSON RECIBIDO --> " + result); 

    } catch (IOException ex) { 
     //screen.requestFailed(ex.toString()); 
     System.out.println("FALLÓ:: " + ex); 

    } catch (Exception e) { 
     e.printStackTrace();   
    }   
}