繁体   English   中英

将JSON数据发送到服务器时出现Android错误

[英]Android error in sending json data to server

我正在使用以下代码将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", "a@g.com");

                    // 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 17:37:42.500:E / AndroidRuntime(1289):java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.demotest / com.example.demotest.MainActivity}:java.lang.NullPointerException:println需要消息

排队

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

e.getLocalizedMessage()提供null,因此Lod.d()提供异常。

只需更换

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM