在Android

时间:2016-03-22 16:23:15

标签: java android json eclipse

我在android中实现GCM。我按照" http://hmkcode.com/android-google-cloud-messaging-tutorial/"中给出的步骤进行操作。 。  我从android端获得了regId。我在Java Project(eclipse)中输入了它。在Java项目中,我导入了jackson-all-1.9.0.jar。 我在这个JavaProject中共有3个java文件

1)Content.java

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class Content implements Serializable{
    private List<String> registration_ids;
    private Map<String,String> data;

    public void addRegId(String regId){
        if(registration_ids == null)
            registration_ids = new LinkedList<String>();
        registration_ids.add(regId);
    }

    public void createData(String title, String message){
        if(data == null)
            data = new HashMap<String,String>();

        data.put("title", title);
        data.put("message", message);
}
}

2)POST2GCM.java

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import org.codehaus.jackson.map.ObjectMapper;


public class POST2GCM {

    public static void post(String apiKey, Content content){

        try{

        // 1. URL
        URL url = new URL("https://android.googleapis.com/gcm/send");

        // 2. Open connection
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // 3. Specify POST method
        conn.setRequestMethod("POST");

        // 4. Set the headers
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key="+apiKey);

        conn.setDoOutput(true);

            // 5. Add JSON data into POST request body

            //`5.1 Use Jackson object mapper to convert Contnet object into JSON
            ObjectMapper mapper = new ObjectMapper();

            // 5.2 Get connection output stream
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

            // 5.3 Copy Content "JSON" into

            mapper.writeValue(wr, content);

            // 5.4 Send the request
            wr.flush();

            // 5.5 close
            wr.close();

            // 6. Get the response
            int responseCode = conn.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 7. Print result
            System.out.println(response.toString());

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

3)App.java

public class App {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println( "Sending POST to GCM" );

        String apiKey = "my api key which i got from //console.developers.google.com";
        Content content = createContent();

        POST2GCM.post(apiKey, content);
    }
     public static Content createContent(){

            Content c = new Content();

            c.addRegId("MyRegKey which i got from android side");
            c.createData("Test Title", "Test Message");

            return c;
        }
}

我得到的错误是:

org.codehaus.jackson.map.JsonMappingException: No serializer found for class Content and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
    at org.codehaus.jackson.map.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:52)
    at org.codehaus.jackson.map.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:25)
    at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
    at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
    at org.codehaus.jackson.map.ObjectMapper._configAndWriteValue(ObjectMapper.java:2575)
    at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:2065)
    at POST2GCM.post(POST2GCM.java:45)
    at App.main(App.java:14)

任何人都可以帮我吗? 我没有找到任何具体的答案..曾经发布但是那些没有解决问题,这个错误是不变的。 提前谢谢。

2 个答案:

答案 0 :(得分:1)

registration_ids课程中将变量dataContent公开。

public class Content implements Serializable {
    public List<String> registration_ids;
    public Map<String,String> data;
  

jackson api从类或公共getter / setters 读取公共变量时,在您的情况下,变量不公开,而且您没有提供getter / setter,所以例外是。

希望它能运作。

答案 1 :(得分:0)

使用GCM,您可以参考Google的指南:https://developers.google.com/cloud-messaging/android/start

然后您可以参考该指南的样本:https://github.com/googlesamples/google-services/tree/master/android/gcm

在本指南中,您可以从服务器查询客户端或发件人gcm的GCM。我希望它对你有所帮助。