之前我们已经完成了发送微博的界面设计,现在我们来尝试编写发送一条微博。新浪微博发送文字微博的API文档查看地址:http://open.weibo.com/wiki/Statuses/update
这里采用post方法向新浪提交数据。与获取账号信息一样,我们还是采用HttpClient开源项目,来为发送http请求。
先看post方法:
/*
* 新浪微博发送普通微博post方法
*/
public String doPost(String url, List<NameValuePair> pairs)
throws OAuthMessageSignerException,
OAuthExpectationFailedException, OAuthCommunicationException,
ClientProtocolException, IOException {
HttpPost postRequest = new HttpPost(url);
postRequest.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));//对传入的参数进行UTF-8编码,然后写入到Entity中
// 关闭Expect:100-Continue握手
// 100-Continue握手需谨慎使用,因为遇到不支持HTTP/1.1协议的服务器或者代理时会引起问题
postRequest.getParams().setBooleanParameter(
CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
consumer.sign(postRequest);//对请求进行OAuth认证签名
System.out.println(postRequest.getRequestLine().getUri());
HttpResponse response = null;
response = new DefaultHttpClient().execute(postRequest);//发送请求
//String result = parseStringFromEntity(response.getEntity());
return result;
}
与获取账号信息一样,我们在外部通过NameValuePair讲参数传入到请求中。
然后我们为发送按钮,添加一个监听器
sendStatus = (ImageButton) findViewById(R.id.send_right);
sendStatus.setOnClickListener(new sendStatusListener());
取得EditText中用户输入的文字
text = (EditText) findViewById(R.id.editStatus);
String statustext = text.getText().toString();
给EditText设置一个监听器,用来监控用户输入的字符数
text.addTextChangedListener(new textWatcher());
/*
* 监控EditText改变情况,记录输入的字符数
*/
class textWatcher implements TextWatcher {
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
textcount.setText("" + text.getText().toString().length());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
看下发送微博监听器中的代码:
/*
* 发送微博按钮的监听
*/
class sendStatusListener implements OnClickListener {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
WeiBoClient weibo = new WeiBoClient(SinaConstant.CONSUMER_KEY,
SinaConstant.CONSUMER_SECRET, access_token, access_secret);
List<NameValuePair> params = new ArrayList<NameValuePair>();
BasicNameValuePair sourcepair = new BasicNameValuePair("source", SinaConstant.CONSUMER_SECRET);
BasicNameValuePair statuspair = new BasicNameValuePair("status", status);
params.add(sourcepair);
params.add(statuspair);
weibo.doPost("http://api.t.sina.com.cn/statuses/update.json", params);
}
}
WeiBoClient类参考Android:SNS客户端开发二:获取账号资料中的内容,我们只需要将本文章开始的post方法添加到其中就可以了。