android 返回字符串,android – 如何从异步回调使用Retrofit返回String或JSONObject?

我想到了。这是尴尬,但它是非常简单…临时解决方案可能是这样的:

public void success(Response response, Response ignored) {

TypedInput body = response.getBody();

try {

BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()));

StringBuilder out = new StringBuilder();

String newLine = System.getProperty("line.separator");

String line;

while ((line = reader.readLine()) != null) {

out.append(line);

out.append(newLine);

}

// Prints the correct String representation of body.

System.out.println(out);

} catch (IOException e) {

e.printStackTrace();

}

}

但是如果你想直接回调更好的方法就是使用Converter。

public class Main {

public interface ApiService {

@GET("/api/")

public void getJson(Callback callback);

}

public static void main(String[] args) {

RestAdapter restAdapter = new RestAdapter.Builder()

.setClient(new MockClient())

.setConverter(new StringConverter())

.setEndpoint("http://www.example.com").build();

ApiService service = restAdapter.create(ApiService.class);

service.getJson(new Callback() {

@Override

public void success(String str, Response ignored) {

// Prints the correct String representation of body.

System.out.println(str);

}

@Override

public void failure(RetrofitError retrofitError) {

System.out.println("Failure, retrofitError" + retrofitError);

}

});

}

static class StringConverter implements Converter {

@Override

public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {

String text = null;

try {

text = fromStream(typedInput.in());

} catch (IOException ignored) {/*NOP*/ }

return text;

}

@Override

public TypedOutput toBody(Object o) {

return null;

}

public static String fromStream(InputStream in) throws IOException {

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

StringBuilder out = new StringBuilder();

String newLine = System.getProperty("line.separator");

String line;

while ((line = reader.readLine()) != null) {

out.append(line);

out.append(newLine);

}

return out.toString();

}

}

public static class MockClient implements Client {

@Override

public Response execute(Request request) throws IOException {

URI uri = URI.create(request.getUrl());

String responseString = "";

if (uri.getPath().equals("/api/")) {

responseString = "{result:\"ok\"}";

} else {

responseString = "{result:\"error\"}";

}

return new Response(request.getUrl(), 200, "nothing", Collections.EMPTY_LIST,

new TypedByteArray("application/json", responseString.getBytes()));

}

}

}

如果你知道如何改进这个代码 – 请随时写下来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值