[英]Java Android AsyncHttpClient convert byte[]responseBody to InputStream
我想創建一個返回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]為空但登錄onSuccess時遇到問題:
Log.e("is" , convertStreamToString(is[0]));
不是null為什么我有null對象is [0]?
因為client.post
是異步調用,而return is[0]
是同步的。 這意味着只要異步調用尚未完成, is[0]
為null。 一種解決方法是使sendGetDataRequest
返回void
,而接受回調,例如
public static void sendGetDataRequest(final YourCallback callback, ...)
創建一個名為YourCallback
的新接口
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
來完成上述所有操作。 這是個人喜好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.