0
我試圖從中央銀行獲得匯率。不幸的是,他們沒有API,可以使用JSON提供數據。僅限於XML。我使用的是retrogit 2.我已經創建了兩個類,它們描述了xml,我從web站點獲得了什麼。但是當我試圖獲得回調的迴應時,我得到了一個404錯誤代碼。也許我的@GET
方法不正確?請幫幫我!使用改進解析XML 2
第一個XML片段。它包含一個日期貨幣數組:
<ValCurs Date="14.01.2017" name="Foreign Currency Market">
<Valute ID="R01010">
<NumCode>036</NumCode>
<CharCode>AUD</CharCode>
<Nominal>1</Nominal>
<Name>Австралийский доллар</Name>
<Value>44,5156</Value>
</Valute>
這裏是我的接口:
public interface CbClient {
@GET("/XML_daily.asp")
Call<ValuteOnDate> getValuteOnDate();
}
和服務生成器類:...
public class ServiceGenerator {
public static final String API_BASE_URL = "http://www.cbr.ru/scripts/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(SimpleXmlConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceClass);
}
}
這裏是MainActivity類別: ...
public class MainActivity extends AppCompatActivity {
private static final String TAG = "TestRetrofitClien";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CbClient client = ServiceGenerator.createService(CbClient.class);
Call<ValuteOnDate> call = client.getValuteOnDate();
call.enqueue(new Callback<ValuteOnDate>() {
@Override
public void onResponse(Call<ValuteOnDate> call, Response<ValuteOnDate> response) {
try {
if (response.isSuccessful()) {
ValuteOnDate valuteOnDate = call.execute().body();
Log.i(TAG,"valuteOnDate: " + valuteOnDate);
ValuteOnDate valuteFromResponse = response.body();
Log.i(TAG,"valuteFromResponse: " + valuteFromResponse);
}else {
Log.e(TAG, "Retrofit Response: " + response.errorBody().string());
Log.d(TAG, "Error message: " + response.raw().message());
Log.d(TAG,"Error code: " + String.valueOf(response.raw().code()));
}
} catch (IOException e) {
Log.e("LOG", "Exeption: " + e);
}
}
@Override
public void onFailure(Call<ValuteOnDate> call, Throwable t) {
}
});
}
}
你能發佈錯誤消息嗎?也許刪除@GET中的前導斜槓(「/ XML_daily.asp」) –
是的。已經修復它。這是一個問題。如果您發表評論作爲答案 - 我會接受它。 – Kroha