我想要对URL进行POST调用,并且作为响应,我只得到一个字符串“ ok”或“ no”。
public interface registerAPI { @FormUrlEncoded @POST("addDevice.php") CallinsertUser( @Field("name") String devicename, @Field("username") String regid); }
所以我只想给POST方法两个参数,我想要一个字符串。在服务器上的PHP脚本中,有类似以下内容:
所以我打电话给我的Android手机:
Retrofit adapter = new Retrofit.Builder() .baseUrl("http://root.url.net/") .addConverterFactory(GsonConverterFactory.create()) //I dont want this.. .build(); registerAPI api = adapter.create(registerAPI.class); Callcall = api.insertUser(name,regid); call.enqueue(new Callback () { @Override public void onResponse(Response response, Retrofit retrofit) { Log.i("Error",response.message()); } @Override public void onFailure(Throwable t) { Log.d("Error", " Throwable is " +t.toString()); } }); 因此,当我在Throwable中运行此命令时,收到以下消息:
Unable to create converter for class java.lang.String我是否只需要为字符串响应编写自己的转换器?我该怎么做?还是有更好的方法来做到这一点?
问候
1> Klatschen..:好的答案是编写自己的转换器。像这样:
public final class ToStringConverterFactory extends Converter.Factory { @Override public ConverterfromResponseBody(Type type, Annotation[] annotations) { //noinspection EqualsBetweenInconvertibleTypes if (String.class.equals(type)) { return new Converter () { @Override public Object convert(ResponseBody responseBody) throws IOException { return responseBody.string(); } }; } return null; } @Override public Converter, RequestBody> toRequestBody(Type type, Annotation[] annotations) { //noinspection EqualsBetweenInconvertibleTypes if (String.class.equals(type)) { return new Converter () { @Override public RequestBody convert(String value) throws IOException { return RequestBody.create(MediaType.parse("text/plain"), value); } }; } return null; } } 您必须这样称呼它:
Retrofit adapter = new Retrofit.Builder() .baseUrl("http://root.url.net/") .addConverterFactory(new ToStringConverterFactory()) .build(); registerAPI api = adapter.create(registerAPI.class); Callcall = api.insertUser(name,regid); 您会收到以下响应:
call.enqueue(new Callback() { @Override public void onResponse(Response response, Retrofit retrofit) { Log.i("http","innen: " + response.message()); Log.i("http","innen: " + response.body()); // here is your string!! } @Override public void onFailure(Throwable t) { Log.d("http", " Throwable " +t.toString()); } });