我有一个要从本地数据库(如果可用)或其他远程服务器检索的对象列表。我正在使用 RxJava Observables(数据库使用 SqlBrite,远程服务器使用 Retrofit)。
我的查询代码如下:
Observable<List<MyObject>> dbObservable = mDatabase
.createQuery(MyObject.TABLE_NAME,MyObject.SELECT_TYPE_A)
.mapToList(MyObject.LOCAL_MAPPER);
Observable<List<MyObject>> remoteObservable = mRetrofitService.getMyObjectApiService().getMyObjects();
return Observable.concat(dbObservable, remoteObservable)
.first(new Func1<List<MyObject>, Boolean>() {
@Override
public Boolean call(List<MyObject> myObjects) {
return !myObjects.isEmpty();
}
});
Run Code Online (Sandbox Code Playgroud)
我看到第一个 observable 正在运行并使用空列表命中第一个方法,但是改造后的 observable 没有运行,没有网络请求。如果我切换 observable 的顺序,或者只是返回远程 observable,它会按预期工作,它会访问远程服务器并返回对象列表。
为什么远程 observable 在这种情况下无法运行?当我首先将 observables 与 db 连接起来,然后再进行改造时,不会调用订阅者的 onNext、orError 和 onComplete 方法。
谢谢!
我已经通过本教程(http://www.duchess-france.org/accelerator-time-series-and-prediction-with-android-cassandra-and-spark/)创建了一个加速度计 Rest API,只是为了看看端点 ( http://192.168.0.104/acceleration )本地主机服务器上的数据值。但是我遇到了“无法为retrofit2.Response创建调用适配器”的错误
但是在教程中使用了 Retrofit (< 2.0),我使用的是 Retorfit2.0 (2.1)。因此,根据更新的库进行了很少的更改。
这是我下面的AccelerometerAct.java
package accelerometer.sensor.com.acceleration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Date;
import accelerometer.sensor.com.acceleration.model.Acceleration;
import retrofit2.Retrofit;
public class AccelerometerAct extends AppCompatActivity implements SensorEventListener{
private String restURL;
private TextView acceleration;
private Button myStartButton;
private Button myStopButton;
private AccelerometerAPI accelerometerAPI;
private SensorManager sm;
private Sensor accelerometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.accelerometer_activity); …Run Code Online (Sandbox Code Playgroud) 我在尝试使用改造将图像上传到服务器时遇到以下错误,api 接收标头授权令牌,_method = "put" 和 image = "imageName.jpg" 作为参数,其他所有内容都是可选的,任何帮助将不胜感激。
java.io.FileNotFoundException:/storage/emulated/0/Download/space-wallpaper-21.jpg:打开失败:EACCES(权限被拒绝)
userImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("*/*");
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, …Run Code Online (Sandbox Code Playgroud) 我正在为Retrofit创建一个通用的API层
这是我的服务类:
public interface ApiService {
@POST("api/authenticate")
Call<Class> postData(@Body Class postBody);
}
public void postRequest(String actionUrl,GenericModelClass postBodyModel){
mApiService.postData(postBodyModel.getClass()).enqueue(new Callback<Class>() {
@Override
public void onResponse(Call<Class> call, Response<Class> response) {
response.getClass().getComponentType();
Log.d("TFFF", response.toString());
}
@Override
public void onFailure(Call<Class> call, Throwable t) {
Log.d("TFFF", t.toString());
}
});
}
Run Code Online (Sandbox Code Playgroud)
但是这个给了我:
java.lang.UnsupportedOperationException:尝试序列化java.lang.Class:a2a.rnd.com.a2ahttplibrary.retrofit.model.User.忘了注册一个类型适配器?
我想User从泛型类型中获取类型,但我得到此异常.
我不明白其中的区别,我编写了一个示例,其中我的应用程序使用带有Retrofit2的POST请求将用户名和密码发送到服务器。
我首先尝试在接口方法中使用@Body标签发送请求:
@POST("/testproject/login.php")
Call<TestResponse> sendUsernamePassword(@Body UserData userData);
Run Code Online (Sandbox Code Playgroud)
但是我的login.php响应没有收到任何正文标签(用户名,密码)。
然后,我更改使用FormEncoding发送请求的方法:
@FormUrlEncoded
@POST("/testproject/login.php")
Call<TestResponse> sendUsernamePassword(@Field("username")String username,
@Field("password")String password);
Run Code Online (Sandbox Code Playgroud)
它开始起作用,但是我不明白为什么改造无法使用@Body注释发送帖子请求。
这是login.php文件
<?php
if (isset($_POST['username']) && isset($_POST['password'])) {
$response['status'] = 'success';
$response['username'] = $_POST['username'] . " received";
$response['password'] = $_POST['password'] . "received";
echo json_encode($response);
} else {
$response['status'] = 'failure';
echo json_encode($response);
}
?>
Run Code Online (Sandbox Code Playgroud)
有人可以解释有什么区别,如何解决?
我试图使用改造2来获取json响应.我的json响应如下所示:
[
0 : {
type : "video",
format : "mp4",
size : "10mb"
},
1 : {
type : "audio",
format : "mp3",
size : "10mb"
},
2 : {
type : "text",
format : "pdf",
size : "10mb"
}
]
Run Code Online (Sandbox Code Playgroud)
我的模型类应该怎么样?我无法理解,因为它有动态键.
嗨,我正在尝试学习 rxjava2。我正在尝试使用 rxjava2 调用 API,并使用改造来构建 URL 并将 JSON 转换为 Moshi。
我想将Observable模式与retrofit. 有谁知道怎么做?任何标准和最佳方法,例如用于错误处理的包装器等等?
应用模块.kt
@Provides
@Singleton
fun provideRetrofit(moshi: Moshi, okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create(moshi))
.baseUrl(BuildConfig.BASE_URL)
.client(okHttpClient)
.build()
}
Run Code Online (Sandbox Code Playgroud)
ApiHelperImpl.kt
@Inject
lateinit var retrofit: Retrofit
override fun doServerLoginApiCall(email: String, password: String): Observable<LoginResponse> {
retrofit.create(RestApi::class.java).login(email, password)
}
Run Code Online (Sandbox Code Playgroud)
我doServerLoginApiCall从LoginViewModel下面这样打电话
登录视图模型.kt
fun login(view: View) {
if (isEmailAndPasswordValid(email, password)) {
ApiHelperImpl().doServerLoginApiCall(email, password)
}
}
Run Code Online (Sandbox Code Playgroud)
RestApi.kt
interface RestApi {
@FormUrlEncoded
@POST("/partner_login")
fun login(@Field("email") email: String, @Field("password") password: …Run Code Online (Sandbox Code Playgroud) 我已经看到有关此问题的其他线程,但无法得到任何正确的答案。
@POST("task/GetAllTasks")
Call<MyTask> getMyTasks(@Header("Authorization") String token, @Query("EmployeeId") String emp);
Run Code Online (Sandbox Code Playgroud)
这就是我的调用方式,起初我认为这是由于GET请求数据限制,因为 GET 施加了数据限制,然后我将请求从 GET 更改为 POST 但问题仍然存在。
ApiUtils.getTaskService().getMyTasks(apiToken, employeeId).enqueue(new Callback<MyTask>() {
@Override
public void onResponse(Call<MyTask> call, Response<MyTask> response) {
// ... Successful code goes here
}
@Override
public void onFailure(Call<MyTask> call, Throwable t) {
//.. This block of code executing now :(
}
}
Run Code Online (Sandbox Code Playgroud)
总是onFailure被调用。我已经在 Postman 上测试了同样的请求,它正在返回数据。Content-Length 是content-length ?45720
它确实适用于少量数据,因为我已经在 Dev 数据库上对其进行了测试,该数据库具有较小的数据量,但在 Live 环境中它不断引起问题。
请提出一个解决方案,或者我应该为此离开 Retrofit 并转向原生 Android 库?
编辑:我们可以在改造中增加请求超时,如果是,那么如何?
我已经设法让它在没有动态密钥的情况下工作。通过使用此json遵循本教程:
目前,我正在使用 Retrofit 并尝试使用动态键获得响应。但是,响应正文始终为空:
这是响应格式:
{
"dynamic1": {
"cityID": "id1",
"priceRange": 15
},
"dynamic2": {
"cityID": "id2",
"priceRange": 15
}
}
Run Code Online (Sandbox Code Playgroud)
在 APIUtils.java 中
public static CityService getCitiesService() {
return RetrofitClient.getClient(BASE_URL).create(CityService.class);
}
Run Code Online (Sandbox Code Playgroud)
在 CityService.java 中
public interface CityService {
@GET("/SAGetStrollAwayCity")
Call<CityResponse> getCities();
@GET("/SAGetStrollAwayCity")
Call<CityResponse> getCities(@Query("tagged") String tags);
}
Run Code Online (Sandbox Code Playgroud)
在 CityResponse.java 中:
public class CityResponse {
/*@SerializedName("results")
@Expose*/ // is this the correct way?
private Map<String, CityDetails> city = new HashMap<>();
public Map<String, CityDetails> getCity() {
return …Run Code Online (Sandbox Code Playgroud) 我目前正在尝试使用 Kotlin 中的 Retrofit 从服务器获取 JSONArray。这是我正在使用的界面:
interface TripsService {
@GET("/coordsOfTrip{id}")
fun getTripCoord(
@Header("Authorization") token: String,
@Query("id") id: Int
): Deferred<JSONArray>
companion object{
operator fun invoke(
connectivityInterceptor: ConnectivityInterceptor
):TripsService{
val okHttpClient = OkHttpClient.Builder().addInterceptor(connectivityInterceptor).build()
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://someurl.com/")
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(TripsService::class.java)
}
}
}
Run Code Online (Sandbox Code Playgroud)
所需的网址是: https://someurl.com/coordsOfTrip?id=201
我收到以下错误消息:
retrofit2.HttpException:不允许使用 HTTP 405 方法
我知道 URL 有效,因为我可以通过浏览器访问它。
有人可以帮我确定我做错了什么吗?