gpt4 book ai didi

Java Android AsyncHttpClient 将 byte[]responseBody 转换为 InputStream

转载 作者:行者123 更新时间:2023-12-02 13:09:06 25 4
gpt4 key购买 nike

我想创建一个返回 InputStream 的方法,我这样做了:

 public static InputStream sendGetDataRequest(Context context,
String version, String power, String lon, String lat, String radius) throws MalformedURLException, ConnectTimeoutException, IOException

{
AsyncHttpClient client = new AsyncHttpClient();
String url = Util.getServerUrl(context) + "/GetData";
// ContentValues values=new ContentValues();
RequestParams values = new RequestParams();

values.put("token", String.valueOf(E_Gps.TOKEN));
values.put("xml", login_xml);
StringEntity entity = null;
try {
entity = new StringEntity(values.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
entity.setContentType(new BasicHeader("Content-Type","application/xml"));
final InputStream[] is = new InputStream[1];
final InputStream inputStream;
client.post(context,url,values , new AsyncHttpResponseHandler(Looper.getMainLooper()) {

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.e("success_noti", new String(responseBody) + "");
is[0] = new ByteArrayInputStream(responseBody);
Log.e("Status " , statusCode + " ");
Log.e("is" , convertStreamToString(is[0]));
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("success_noti", new String(responseBody) + "");
Log.e("Status " , statusCode + " ");


}
});
return is[0];
}

当我返回 is[0] is a null 但当我登录 onSuccess 时,我遇到了问题:

Log.e("is" , convertStreamToString(is[0]));

is not null 为什么我有 null 对象 is[0] ?

最佳答案

因为client.post是异步调用,而return is[0]是同步调用。这意味着只要异步调用尚未完成,is[0] 就为 null。解决方法之一是让 sendGetDataRequest 返回 void 并接受回调,例如

public static void sendGetDataRequest(final YourCallback callback, ...)

创建一个名为YourCallback的新接口(interface)

public interface YourCallback{
void onSuccess(String string);
void failure();
}

并在异步方法中使用该回调

 client.post(context,url,values , new AsyncHttpResponseHandler(Looper.getMainLooper()) {

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
callback.onSuccess(convertStreamToString(is[0]));
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
callback.onFailure();
}
}

最后你像这样调用静态方法

sendGetDataRequest(new YourCallback(){/* Override the methods */}, ...);

顺便说一句,您还可以使用 android 包中的 AsyncTask 来完成上述所有操作。这是个人喜好。

关于Java Android AsyncHttpClient 将 byte[]responseBody 转换为 InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44025965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com