我想从“OpenExchange rates”导入“latest.jason”以获取最新的汇率。
但是当我写“AsyncHttpClient”时,它会创建以下“未实现的类”:
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// TODO Auto-generated method stub
}
但我想要 - (运行)
public void onSuccess(String arg2) {
Log.i("MYFIRSTAPP" , "HTTP Successs");
try {
JSONObject jsonObj = new JSONObject(arg2);
JSONObject ratesObject = jsonObj.getJSONObject("rates");
Double gbpRate = ratesObject.getDouble("GBP");
Double eurRate = ratesObject.getDouble("EUR");
Log.i("MYFIRSTAPP", "GBP" +gbpRate);
Log.i("MYFIRSTAPP", "EUR" +eurRate);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我得到的问题是: onSuccess将“int arg0,Header [] arg1,byte [] arg2”作为参数......
但我想要 - “String arg2”
答案 0 :(得分:0)
试试这个...
AsyncHttpClient client = new AsyncHttpClient();
client.get(URL, new AsyncHttpResponseHandler()
{
@Override
public void onFailure(int statusCode, Header[] header, byte[] content,
Throwable error)
{
// show error messages here
super.onFailure(statusCode, error, content);
}
@Override
public void onSuccess(int statusCode, Header[] header, byte[] content)
{
if (statusCode == 200)
{
try
{
//convert byte[] to string.
String contentStr = content.toString();
Log.i("Tag", "content" + URL + " " + contentStr );
//String to JSONObject.
JSONObject jsonObj = new JSONObject(contentStr );
JSONObject ratesObject = jsonObj.getJSONObject("rates");
Double gbpRate = ratesObject.getDouble("GBP");
Double eurRate = ratesObject.getDouble("EUR");
Log.i("MYFIRSTAPP", "GBP" + gbpRate);
Log.i("MYFIRSTAPP", "EUR" + eurRate);
}
catch (Exception e)
{
e.toString();
}
}
else
{
// show network error toast here;
}
}
});
快乐的编码......
答案 1 :(得分:0)
AsyncHttpResponseHandler及其子类中有onSuccess
和onFailure
种方法的多种变体。
最适合处理JSON数据的是JsonHttpResponseHandler