【文件属性】:
文件名称:新浪微博授权代码及测试结果.zip
文件大小:46KB
文件格式:ZIP
更新时间:2014-02-16 08:24:01
新浪微博授权代码及测试结果.zip
/**
* 测试新浪微博API
* @author syn
* @date 2010/12/22
*/
public class TestActivity extends Activity
{
private static final String BASE_URL = "http://api.t.sina.com.cn/"; //API接口
private static final String CONSUMER_KEY = "270793661"; //你申请的Key
private static final String HEADER_AUTHO = "Authorization"; //Authorization
private static final String HEADER_BASIC = "Basic "; //Basic
private static final String ERROR = "MyError"; //错误
List myTestList;
/**
* 测试用的类,用于解析JSON,因为只是测试,所以乱写一下
*/
public class myTest
{
private Date created_at; //返回微博发布的时间
private String text; //微博内容
private User user; //微博用户信息
public myTest(JSONObject object) throws JSONException //解析JSON文件
{
text=""; user=null;
created_at=new Date(object.getString("created_at"));
text=object.getString("text");
user=new User(object.getJSONObject("user"));
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
String tailUrl="statuses/public_timeline.json"; //我要获得的是最新的公共微博
String response=getResponse(tailUrl, MainActivity.loginUser);//调用提交函数,此函数是核心部分
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.test);
TextView textView01=(TextView)findViewById(R.id.test);
if(response.startsWith(ERROR))
textView01.setText("error");
else
{
JSONArray array;
try
{
array = new JSONArray(response);
for (int i = 0; i < array.length(); i++)
{
myTest mytest= new myTest(array.getJSONObject(i));
//myTestList.add(mytest);
String content="Content:"+mytest.text+" Author:"+mytest.user.getNike()+" Date:"+mytest.created_at;
textView01.setText(content);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
/**
* 此函数提交URL,返回访问结果
* @param tailUrl json或者xml的url
* @param user 用户的一个对象
* @return 提交结果
*/
private static String getResponse(String tailUrl,User user)
{
String httpUrl=BASE_URL+tailUrl;
ArrayList postParams=new ArrayList();
postParams.add(new BasicNameValuePair("source",CONSUMER_KEY)); //封装入APP Key
try
{
HttpPost httpRequest = new HttpPost(httpUrl);
httpRequest.setEntity(new UrlEncodedFormEntity(postParams,HTTP.UTF_8)); //把参数放入Entity
httpRequest.addHeader(HEADER_AUTHO, HEADER_BASIC+user.encodeBase64NamePass()); //这里就是给用户的用户名和密码加密,然后放入http头
httpRequest.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest); //提交
int statusCode=httpResponse.getStatusLine().getStatusCode(); //获得结果码200是正确
if ( statusCode== HttpStatus.SC_OK)
{
String strResult = EntityUtils.toString(httpResponse.getEntity());
Log.e("WeiboKu", "strResult :"+strResult);
return strResult;
}
else
{
Log.e("WeiboKu", "strResult Error:"+statusCode);
return ERROR+String.valueOf(statusCode);
}
}
catch (Exception e)
{
Log.e("WeiboKu", "getResponse Exception:"+e.getMessage());
return ERROR+e.getMessage().toString();
}
}
}
【文件预览】:
新浪微博授权代码及测试结果.doc