我需要将图片发布到 Tumblr。我读了这个http://www.tumblr.com/docs/en/api/v2#auth我开始知道我需要获取用户信息才能获取博客名称。我使用了用于 Twitter 身份验证的相同代码,更改了 URL 并成功加载了 Tumblr webview。我使用以下代码进行身份验证并获取用户信息。
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.twitter.imageupload.R;
import com.twitter.imageupload.SecondClass;
import com.twitter.imageupload.TwitterImageUpload;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.http.HttpParameters;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.http.AccessToken;
import twitter4j.http.OAuthAuthorization;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
public class Tumblr_Web_View extends Activity {
SharedPreferences settings;
public static final String PREFS_NAME = "GREATEST_THINGS";
SharedPreferences.Editor editor;
final String TAG = getClass().getName();
Button cancel_button;
public static String usr_img, log_res, log_id;
private OAuthConsumer consumer;
private OAuthProvider provider;
WebView tumblr_web_view;
String tweet_Sign_in;
static twitter4j.Twitter twitter;
public static String userName;
public static URL twt_img_url;
AccessToken accessToken;
SharedPreferences twtuname_pref;
SharedPreferences userpref;
public static final String USER_PREF = "TWITTER_USER";
SharedPreferences.Editor usereditor;
SharedPreferences twtlogpref;
public static SharedPreferences.Editor twtlogeditor;
public static final String TWTPREF_LOGIN = "LOGIN ID";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.tumblr_web_view);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
tumblr_web_view = (WebView) findViewById(R.id.tumblr_web_view);
twtuname_pref = this.getSharedPreferences("user_pref", 1);
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
userpref = getSharedPreferences(USER_PREF, 0);
twtlogpref = getSharedPreferences(TWTPREF_LOGIN, 0);
try {
this.consumer = new CommonsHttpOAuthConsumer(
Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
this.provider = new CommonsHttpOAuthProvider(Constants.REQUEST_URL,
Constants.ACCESS_URL, Constants.AUTHORIZE_URL);
} catch (Exception e) {
Log.e(TAG, "Error creating consumer / provider", e);
}
Log.i(TAG, "Starting task to retrieve request token.");
// new OAuthRequestTokenTask(this,consumer,provider).execute();
try {
Log.i(TAG, "Retrieving request token from Google servers");
final String url = provider.retrieveRequestToken(consumer,
Constants.OAUTH_CALLBACK_URL);
Log.i(TAG, "Popping a browser with the authorize URL : " + url);
// Intent intent = new Intent(Intent.ACTION_VIEW,
// Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP |
// Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
// this.startActivity(intent);
tumblr_web_view.loadUrl(url);
} catch (Exception e) {
Log.e(TAG, "Error during OAUth retrieve request token", e);
}
}
/**
* Called when the OAuthRequestTokenTask finishes (user has authorized the
* request token). The callback URL will be intercepted here.
*/
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
final Uri uri = intent.getData();
if (uri != null
&& uri.getScheme().equals(Constants.OAUTH_CALLBACK_SCHEME)) {
Log.i(TAG, "Callback received : " + uri);
Log.i(TAG, "Retrieving Access Token");
new RetrieveAccessTokenTask(this, consumer, provider, prefs)
.execute(uri);
// finish();
}
}
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
@SuppressWarnings("unused")
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,
OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs = prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and
* oauth_token_secret for future API calls.
*/
@Override
protected Void doInBackground(Uri... params) {
Uri uri = params[0];
Log.v("uri >>", uri + "");
String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
consumer.setTokenWithSecret(consumer.getToken(),
consumer.getTokenSecret());
// provider.retrieveAccessToken(consumer, oauth_verifier);
Log.v("getToken", consumer.getToken());
Log.v("getTokenSecret", consumer.getTokenSecret());
Editor uname_editor = twtuname_pref.edit();
uname_editor.putString("token", consumer.getToken());
uname_editor.putString("secret_token",
consumer.getTokenSecret());
uname_editor.putString("login_status", "already_logged");
uname_editor.commit();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"http://api.tumblr.com/v2/user/info");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse");
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
System.out.println("Returning value of doInBackground :"
+ stringBuilder.toString());
} catch (ClientProtocolException cpe) {
System.out
.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
}
}
我收到以下错误。
06-06 23:06:20.084: I/System.out(20264): Returning value of doInBackground :{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}
我做错了什么?
更新: 现在成功获取到用户信息了。获取用户博客名称。
public class RetrieveAccessTokenTask extends AsyncTask<Uri, Void, Void> {
@SuppressWarnings("unused")
private Context context;
private OAuthProvider provider;
private OAuthConsumer consumer;
private SharedPreferences prefs;
public RetrieveAccessTokenTask(Context context, OAuthConsumer consumer,
OAuthProvider provider, SharedPreferences prefs) {
this.context = context;
this.consumer = consumer;
this.provider = provider;
this.prefs = prefs;
}
/**
* Retrieve the oauth_verifier, and store the oauth and
* oauth_token_secret for future API calls.
*/
@Override
protected Void doInBackground(Uri... params) {
Uri uri = params[0];
Log.v("uri >>", uri + "");
String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
try {
consumer.setTokenWithSecret(consumer.getToken(),
consumer.getTokenSecret());
provider.retrieveAccessToken(consumer, oauth_verifier);
Log.v("getToken", consumer.getToken());
Log.v("getTokenSecret", consumer.getTokenSecret());
Editor uname_editor = twtuname_pref.edit();
uname_editor.putString("token", consumer.getToken());
uname_editor.putString("secret_token",
consumer.getTokenSecret());
uname_editor.putString("login_status", "already_logged");
uname_editor.commit();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"http://api.tumblr.com/v2/user/info");
try {
consumer.sign(httpGet);
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("httpResponse");
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
System.out.println("Returning value of doInBackground :"
+ stringBuilder.toString());
} catch (ClientProtocolException cpe) {
System.out
.println("Exception generates caz of httpResponse :"
+ cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out
.println("Second exception generates caz of httpResponse :"
+ ioe);
ioe.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, "OAuth - Access Token Retrieval Error", e);
}
return null;
}
}
我试图将图片发布到已登录用户的博客中。使用了以下代码。但没有得到回应。
try {
HttpClient client = new DefaultHttpClient();
client.getConnectionManager()
.getSchemeRegistry()
.register(
new Scheme("SSLSocketFactory", SSLSocketFactory
.getSocketFactory(), 443));
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000);
HttpResponse response1;
HttpPost post = new HttpPost(
"http://api.tumblr.com/v2/blog/"+username+".tumblr.com/post");
consumer.sign(post);
JSONObject json_obj_val = new JSONObject();
json_obj_val.put("type", "photo");
json_obj_val.put("caption", "test");
json_obj_val.put("source", "http://50.57.227.117/blacksheep/uploaded/Detailed_images/961314275649aladdins.jpg");
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
StringEntity entity_val = new StringEntity(
json_obj_val.toString());
entity_val.setContentEncoding(new BasicHeader(
HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(entity_val);
response1 = client.execute(post);
String response_string = EntityUtils.toString(response1.getEntity());
Log.v("response >>", response_string);
Log.v("response length >>", response_string.length() + "");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
得到以下回应。代码有什么问题?
06-11 16:24:46.312: V/response >>(27710): {"meta":{"status":400,"msg":"Bad Request"},"response":{"errors":["Post cannot be empty."]}}
最佳答案
我找到了解决方案。我使用以下代码并成功将图像发布到登录用户的博客。
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = null;
String result = null;
HttpPost hpost = new HttpPost("http://api.tumblr.com/v2/blog/" + username + ".tumblr.com/post");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("type", "photo"));
nameValuePairs.add(new BasicNameValuePair("caption", "hello"));
nameValuePairs.add(new BasicNameValuePair("source", "url_of_the_image"));
String debug = "";
try {
hpost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
consumer.sign(hpost);
resp = client.execute(hpost);
result = EntityUtils.toString(resp.getEntity());
Log.v("result >>", result);
} catch (UnsupportedEncodingException e) {
debug += e.toString();
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
关于android - 需要在 android 中将图片发布到 Tumblr 博客,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16968684/
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/
我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只
我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121
我是Rails的新手,所以请原谅简单的问题。我正在为一家公司创建一个网站。那家公司想在网站上展示它的客户。我想让客户自己管理这个。我正在为“客户”生成一个表格,我想要的三列是:公司名称、公司描述和Logo。对于名称,我使用的是name:string但不确定如何在脚本/生成脚手架终端命令中最好地创建描述列(因为我打算将其设置为文本区域)和图片。我怀疑描述(我想成为一个文本区域)应该仍然是描述:字符串,然后以实际形式进行调整。不确定如何处理图片字段。那么……说来话长:我在脚手架命令中输入什么来生成描述和图片列? 最佳答案 对于“文本”数
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Rubysyntaxquestion:Rational(a,b)andRational.new!(a,b)我正在阅读ruby镐书,我对创建有理数的语法感到困惑。Rational(3,4)*Rational(1,2)产生=>3/8为什么Rational不需要new方法(我还注意到例如我可以在没有new方法的情况下创建字符串)?
无论您是想搭建桌面端、WEB端或者移动端APP应用,HOOPSPlatform组件都可以为您提供弹性的3D集成架构,同时,由工业领域3D技术专家组成的HOOPS技术团队也能为您提供技术支持服务。如果您的客户期望有一种在多个平台(桌面/WEB/APP,而且某些客户端是“瘦”客户端)快速、方便地将数据接入到3D应用系统的解决方案,并且当访问数据时,在各个平台上的性能和用户体验保持一致,HOOPSPlatform将帮助您完成。利用HOOPSPlatform,您可以开发在任何环境下的3D基础应用架构。HOOPSPlatform可以帮您打造3D创新型产品,HOOPSSDK包含的技术有:快速且准确的CAD
有人知道在发布新版本的Ruby和Rails时收到电子邮件的方法吗?他们有邮件列表,RubyonRails有一个推特,但我不想听到那些随之而来的喧嚣,我只想知道什么时候发布新版本,尤其是那些有安全修复的版本。 最佳答案 从therailsblog获取提要.http://weblog.rubyonrails.org/feed/atom.xml 关于ruby-on-rails-如何在发布新的Ruby或Rails版本时收到通知?,我们在StackOverflow上找到一个类似的问题:
最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路
有没有一种简单的方法可以将给定的整数格式化为具有固定长度和前导零的字符串?#convertnumberstostringsoffixedlength3[1,12,123,1234].map{|e|???}=>["001","012","123","234"]我找到了解决方案,但也许还有更聪明的方法。format('%03d',e)[-3..-1] 最佳答案 如何使用%1000而不是进行字符串操作来获取最后三位数字?[1,12,123,1234].map{|e|format('%03d',e%1000)}更新:根据theTinMan的