问题描述
我想要对URL进行POST调用,并且作为响应,我只得到一个字符串"ok"或"no".所以我在这里有这样的界面:
I want a POST call on an URL, and as response I just get a String "ok" or "no"..So I have here my interface like this:
public interface registerAPI
{
@FormUrlEncoded
@POST("addDevice.php")
Call<String> insertUser(
@Field("name") String devicename,
@Field("username") String regid);
}
所以我只想给POST方法两个参数,我想要一个字符串.在服务器上的PHP脚本中,是这样的:
So I just want to give the POST method the two parameters, and I want a back a String. In a PHP script on the server, there is something like this:
<?php
if(...)
echo "ok";
else
echo "no";
所以我用Android手机打电话
So I call on my Android-phone:
Retrofit adapter = new Retrofit.Builder()
.baseUrl("http://root.url.net/")
.addConverterFactory(GsonConverterFactory.create()) //I dont want this..
.build();
registerAPI api = adapter.create(registerAPI.class);
Call<String> call = api.insertUser(name,regid);
call.enqueue(new Callback<String>()
{
@Override
public void onResponse(Response<String> response, Retrofit retrofit)
{
Log.i("Error",response.message());
}
@Override
public void onFailure(Throwable t)
{
Log.d("Error", " Throwable is " +t.toString());
}
});
因此,当我在Throwable中运行此命令时,会收到以下消息:
So, when I run this, in Throwable, I get the following message:
Unable to create converter for class java.lang.String
我是否只需要为字符串响应编写自己的转换器?那我该怎么做呢?还是有更好的方法来做到这一点?
Do I have to write my own converter just for a String-response? And how do I do that? Or is there a better way to do this?
致谢
推荐答案
好的答案是编写自己的转换器.像这样:
Ok the answer is to write an own converter. Like this:
public final class ToStringConverterFactory extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> fromResponseBody(Type type, Annotation[] annotations) {
//noinspection EqualsBetweenInconvertibleTypes
if (String.class.equals(type)) {
return new Converter<ResponseBody, Object>() {
@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<String, RequestBody>() {
@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);
Call<String> call = api.insertUser(name,regid);
您会收到以下答复:
call.enqueue(new Callback<String>()
{
@Override
public void onResponse(Response<String> 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());
}
});
这篇关于带字符串响应的改造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!