2014-04-17 73 views
0

我使用下面的代码JSON数据发送到服务器Android的错误JSON数据发送到服务器

 public String POST(String url){ 
      InputStream inputStream = null; 
      String result = ""; 
      try { 

       // 1. create HttpClient 
       HttpClient httpclient = new DefaultHttpClient(); 

       // 2. make POST request to the given URL 
       HttpPost httpPost = new HttpPost(url); 

       String json = ""; 

        // 3. build jsonObject 
       JSONObject jsonObject = new JSONObject(); 
        jsonObject.accumulate("ClientId", "38"); 
       jsonObject.accumulate("FirstName", "NIRMAL"); 
      jsonObject.accumulate("SurName", "kumar"); 
       jsonObject.accumulate("Password", "123"); 
      jsonObject.accumulate("EmailId", "[email protected]"); 

        // 4. convert JSONObject to JSON to String 
       json = jsonObject.toString(); 

      // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
       // ObjectMapper mapper = new ObjectMapper(); 
       // json = mapper.writeValueAsString(person); 

       // 5. set json to StringEntity 
       StringEntity se = new StringEntity(json); 

       // 6. set httpPost Entity 
       httpPost.setEntity(se); 

       // 7. Set some headers to inform server about the type of the content 
       httpPost.setHeader("Accept", "application/json"); 
       httpPost.setHeader("Content-type", "application/json"); 

       // 8. Execute POST request to the given URL 
       HttpResponse httpResponse = httpclient.execute(httpPost); 

      // 9. receive response as inputStream 
       inputStream = httpResponse.getEntity().getContent(); 

       // 10. convert inputstream to string 
       if(inputStream != null) 
       result = convertInputStreamToString(inputStream); 
      else 
        result = "Did not work!"; 

      } catch (Exception e) { 
      Log.d("InputStream", e.getLocalizedMessage()); 
      } 

      // 11. return result 
      return result; 
     } 

,但我得到以下错误:

04-17 22:37:42.500 :E/AndroidRuntime(1289):java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.demotest/com.example.demotest.MainActivity}:java.lang.NullPointerException:println需要一条消息

回答

0

In line

Log.d(“InputStream”,e.getLocalizedMessage());

e.getLocalizedMessage()给出null,因此Lod.d()会给出异常。

只需更换

Log.d( “InputStream的”,e.getLocalizedMessage());

Log.d( “InputStream的”,e.printStackTrace());