gpt4 book ai didi

java - Android 中的自定义异步 Http 客户端

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:01 24 4
gpt4 key购买 nike

我使用 https://github.com/loopj/android-async-http但我认为这可以应用于异步任务( native 任务)

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {

@Override
public void onStart() {
// called before request is started
//Some debugging code here
}

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
//here is the interesting part
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
//Some debugging code here, show retry dialog, feedback etc.
}

@Override
public void onRetry(int retryNo) {
//Some debugging code here-------

}
});

我在许多单独的类(class)中经常使用它。 onStart、onFailure、onRetry到处都是一样的,只是复制粘贴而已,只是onSuccess不一样。

我想尽可能保持我的代码干净并重用我已经编写的代码,所以我的问题是,我如何在一个单独的"file"中进行自定义,然后再重用它。我只需要“OnSuccess”函数。谢谢

----------------------------------------

GET 和 POST 的解决方案(感谢 furkan3ayraktar)

第一个文件RequestListener

package com.classicharmony.krakenmessages.utils.AsyncHttp;
import org.apache.http.Header;
public interface RequestListener {
public void onSuccess(int statusCode, Header[] headers, byte[] response);
}

第二个文件RequestHandler

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;


import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;
import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;

public class RequestHandler {

private static RequestHandler instance;

private AsyncHttpClient client;
private static final boolean SHOW_DEBUG_ALERT_DIALOG = true;

private RequestHandler() {
client = new AsyncHttpClient();

}

public static RequestHandler getInstance() {
if (instance == null) {
instance = new RequestHandler();
}
return instance;
}


public void make_get_Request(final Context context, final String url, final RequestListener listener) {
client.get(url, new AsyncHttpResponseHandler() {

@Override
public void onStart() {
Log.v("▒▒▒▒▒▒▒ GET ", url);
}

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
listener.onSuccess(statusCode, headers, response);
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
Log.e("▒▒▒▒▒▒▒ GET FAILED ", url);
Log.e("▒▒▒▒▒▒▒ GET FAILED ", e.getLocalizedMessage());

if (DUtils.isDebuggable(context) && SHOW_DEBUG_ALERT_DIALOG) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("▒▒▒▒▒ ERROR ▒▒▒▒▒");
String error_msg;
if (errorResponse != null) {
try {
error_msg = String.valueOf(new String(errorResponse, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
error_msg = e.getLocalizedMessage();
}
} else {
error_msg = e.getLocalizedMessage();
}

builder.setMessage(context.getClass().getSimpleName() + " -> " + error_msg)
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

@Override
public void onRetry(int retryNo) {
Log.e("▒▒▒▒▒▒▒ RETRYING ", "....." + String.valueOf(retryNo));

}
});
}

public void make_post_Request(final Context context, final StringEntity entity, final String url, final RequestListener listener) {
client.post(context, url, entity, "application/json", new AsyncHttpResponseHandler() {

@Override
public void onStart() {
Log.v("▒▒▒▒▒▒▒ POST ", url);
}

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
listener.onSuccess(statusCode, headers, response);
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
Log.e("▒▒▒▒▒▒▒ POST FAILED ", url);
Log.e("▒▒▒▒▒▒▒ POST FAILED ", context.getClass().getSimpleName() + " -> " + e.getLocalizedMessage());


if (DUtils.isDebuggable(context) && SHOW_DEBUG_ALERT_DIALOG) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("▒▒▒▒▒ ERROR ▒▒▒▒▒");
String error_msg;
if (errorResponse != null) {
try {
error_msg = String.valueOf(new String(errorResponse, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
error_msg = e.getLocalizedMessage();
}
} else {
error_msg = e.getLocalizedMessage();
}

builder.setMessage(context.getClass().getSimpleName() + " -> " + error_msg)
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}

}

@Override
public void onRetry(int retryNo) {
Log.e("▒▒▒▒▒▒▒ RETRYING ", "....." + String.valueOf(retryNo));
}
});
}

}

用于显示或不显示对话框的第三个“实用程序”。

public static boolean isDebuggable(Context ctx) {
boolean debuggable = false;
X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");
try {
PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
Signature signatures[] = pinfo.signatures;

CertificateFactory cf = CertificateFactory.getInstance("X.509");

for (int i = 0; i < signatures.length; i++) {
ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
if (debuggable)
break;
}
} catch (PackageManager.NameNotFoundException e) {
//debuggable variable will remain false
} catch (CertificateException e) {
//debuggable variable will remain false
}
return debuggable;
}

如何为 POST 调用它的示例:

JSONObject jsonParams = new JSONObject();
StringEntity entity;


try {
jsonParams.put("from_user_id", "dan");
jsonParams.put("to_user_id", "vili");
jsonParams.put("message", "hello world");
entity = new StringEntity(jsonParams.toString());
} catch (JSONException e) {
e.printStackTrace();
return;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return;
}

RequestHandler handler = RequestHandler.getInstance();
handler.make_post_Request(getActivity(), entity, "http://your_server/api/etc", new RequestListener() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
try {
String server_response = String.valueOf(new String(response, "UTF-8"));
Log.v("Server response",server_response);
} catch (UnsupportedEncodingException e1) {

}
}
});

最佳答案

您可以创建自己的 AsyncHttpResponseHandler 空版本,它不实现 onSuccess 方法。

public abstract class OWADVLHttpResponseHandler extends AsyncHttpResponseHandler {

@Override
public void onStart() {}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {}

@Override
public void onRetry(int retryNo) {}
}

您的代码将如下所示:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new OWADVLHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
....
}
});

很明显,你可以在基类中的非覆盖方法中填写一些内容。

关于java - Android 中的自定义异步 Http 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26481137/

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