在Blackberry java OS6 +中发送一个帖子json的正文

时间:2013-06-11 21:32:18

标签: json rest blackberry java-me

我需要将一个POST JSON的正文发送到Blackberry java OS6 +的REST服务。我见过的例子,但不是如何创建这样的身体。然后,我需要在POST中发送之前创建的正文? 我需要发送的身体的一个例子是:

体:

{
  "name" : "my name",
  "password" : "asdf",
  "email" : "mail@mail.com",
  "gender" : 0,
}

服务将返回:

{
   "response": {
     "status": "ok"
   }
}

2 个答案:

答案 0 :(得分:1)

这就是解决方案

只需要将String更改为JSONObject主体。

Solamente tenia que cambiar el cuerpo String a JSONObject。

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

         JSONObject json =  new  JSONObject ( 
                "{"+
                    "'name' : 'test',"+
                    "'email' : 'test@test.com',"+
                    "'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();        
     }        
}

答案 1 :(得分:0)