java - Android Twitter 应用程序无法从 Json 响应创建对象

标签 java android json twitter

我试图简单地从用户下载的 Twitter 流中创建对象。我正在使用 https://github.com/Rockncoder/TwitterTutorial 提供的信息。有人可以帮助确定这段代码是否真的有效吗?有些类有点粗略,例如 Twitter.java 类只是一个 ArrayList,并且只包含下面列出的内容。

我的流程正确吗?任何帮助表示赞赏。

公共(public)类 MainActivity 扩展 ListActivity {

private ListActivity activity;
final static String ScreenName = "riddlemetombers";
final static String LOG_TAG = "rmt";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    activity = this;

    downloadTweets();

}


// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        new DownloadTwitterTask().execute(ScreenName);
    } else {
        Log.v(LOG_TAG, "No network connection available.");
    }
}


// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
    final String CONSUMER_KEY = (String) getResources().getString(R.string.api_key);
    final String CONSUMER_SECRET = (String)getResources().getString(R.string.api_secret);
    final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
    final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";

    @Override
    protected String doInBackground(String... screenNames) {
        String result = null;

        if (screenNames.length > 0) {
            result = getTwitterStream(screenNames[0]);
        }
        return result;
    }

    // onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
    @Override
    protected void onPostExecute(String result) {
        Twitter twits = jsonToTwitter(result);

        // lets write the results to the console as well
        for (Tweet tweet : twits) {
            Log.i(LOG_TAG, tweet.getText());
        }

        // send the tweets to the adapter for rendering
        ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, R.layout.items, twits);
        setListAdapter(adapter);
    }

    // converts a string of JSON data into a Twitter object
    private Twitter jsonToTwitter(String result) {
        Twitter twits = null;
        if (result != null && result.length() > 0) {
            try {
                Gson gson = new Gson();
                twits = gson.fromJson(result, Twitter.class);
                if(twits==null){Log.d(LOG_TAG, "Twits null");}
                else if(twits!=null) {Log.d(LOG_TAG, "Twits NOT null");}
            } catch (IllegalStateException ex) {
                // just eat the exception
            }
        }
        return twits;
    }

    // convert a JSON authentication object into an Authenticated object
    private Authenticated jsonToAuthenticated(String rawAuthorization) {
        Authenticated auth = null;
        if (rawAuthorization != null && rawAuthorization.length() > 0) {
            try {
                Gson gson = new Gson();
                auth = gson.fromJson(rawAuthorization, Authenticated.class);
            } catch (IllegalStateException ex) {
                // just eat the exception
            }
        }
        return auth;
    }

    private String getResponseBody(HttpRequestBase request) {
        StringBuilder sb = new StringBuilder();
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
            HttpResponse response = httpClient.execute(request);
            int statusCode = response.getStatusLine().getStatusCode();
            String reason = response.getStatusLine().getReasonPhrase();

            if (statusCode == 200) {

                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();

                BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                String line = null;
                while ((line = bReader.readLine()) != null) {
                    sb.append(line);
                }
            } else {
                sb.append(reason);
            }
        } catch (UnsupportedEncodingException ex) {
        } catch (ClientProtocolException ex1) {
        } catch (IOException ex2) {
        }
        return sb.toString();
    }

    private String getTwitterStream(String screenName) {
        String results = null;

        // Step 1: Encode consumer key and secret
        try {
            // URL encode the consumer key and secret
            String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
            String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");

            // Concatenate the encoded consumer key, a colon character, and the
            // encoded consumer secret
            String combined = urlApiKey + ":" + urlApiSecret;

            // Base64 encode the string
            String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

            // Step 2: Obtain a bearer token
            HttpPost httpPost = new HttpPost(TwitterTokenURL);
            httpPost.setHeader("Authorization", "Basic " + base64Encoded);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
            String rawAuthorization = getResponseBody(httpPost);
            Authenticated auth = jsonToAuthenticated(rawAuthorization);

            // Applications should verify that the value associated with the
            // token_type key of the returned object is bearer
            if (auth != null && auth.token_type.equals("bearer")) {

                // Step 3: Authenticate API requests with bearer token
                HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);

                // construct a normal HTTPS request and include an Authorization
                // header with the value of Bearer <>
                httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
                httpGet.setHeader("Content-Type", "application/json");
                // update the results with the body of the response
                results = getResponseBody(httpGet);
            }
        } catch (UnsupportedEncodingException ex) {
        } catch (IllegalStateException ex1) {
        }
        return results;
    }
}






@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

推特类(class)

import java.util.ArrayList;

// a collection of tweets
public class Twitter extends ArrayList<Tweet> {
    private static final long serialVersionUID = 1L;
}

推文类(class)

import com.google.gson.annotations.SerializedName;

public class Tweet {

@SerializedName("created_at")
private String DateCreated;

@SerializedName("id")
private String Id;

@SerializedName("text")
private String Text;

@SerializedName("in_reply_to_status_id")
private String InReplyToStatusId;

@SerializedName("in_reply_to_user_id")
private String InReplyToUserId;

@SerializedName("in_reply_to_screen_name")
private String InReplyToScreenName;

@SerializedName("user")
private TwitterUser User;

public String getDateCreated() {
    return DateCreated;
}

public String getId() {
    return Id;
}

public String getInReplyToScreenName() {
    return InReplyToScreenName;
}

public String getInReplyToStatusId() {
    return InReplyToStatusId;
}

public String getInReplyToUserId() {
    return InReplyToUserId;
}

public String getText() {
    return Text;
}

public void setDateCreated(String dateCreated) {
    DateCreated = dateCreated;
}

public void setId(String id) {
    Id = id;
}

public void setInReplyToScreenName(String inReplyToScreenName) {
    InReplyToScreenName = inReplyToScreenName;
}

public void setInReplyToStatusId(String inReplyToStatusId) {
    InReplyToStatusId = inReplyToStatusId;
}

public void setInReplyToUserId(String inReplyToUserId) {
    InReplyToUserId = inReplyToUserId;
}

public void setText(String text) {
    Text = text;
}

public void setUser(TwitterUser user) {
    User = user;
}

public TwitterUser getUser() {
    return User;
}

@Override
public String  toString(){
    return getText();
}
}

我已经做了几次 Log.d(LOG_TAG, Stuff) 来查看我是否得到了东西,它表明我正在得到某种内容。也许问题在于创建数据对象。

最佳答案

不确定为什么要使用 https://github.com/Rockncoder/TwitterTutorial 中的代码.

为什么不使用http://twitter4j.org 。他们给出了使用它的示例。

此外它还支持Twitter 1.1。只需包含 twitter-core.jar 即可编写代码。

希望有帮助。

关于java - Android Twitter 应用程序无法从 Json 响应创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23095646/

相关文章:

java - 获取xml中所有节点的Xpath

将路径解析为多个可选组的 Java 正则表达式

java - 创建从 Java 客户端(在 Android 上)到 Python 服务器的自签名 SSL 套接字

java - 是否可以通过编程方式设置引脚以进行蓝牙配对?

java - 使用java api的Elasticsearch多条件查询

java - 将 minSDK 设置为 Jelly Bean 时我的应用程序崩溃

android - 以编程方式添加多个 fragment

java - 返回嵌套在 mongo 文档中的随机元素

php - 如何在 Symfony 中解析这个 JSON 对象

java - Fasterxml Jackson 自动将非 boolean 值转换为 boolean 值