java—创建网络线程作为方法

ryevplcw  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(442)

我对android的编程非常陌生-请耐心听我说。
我正在使用okhttp构建一个需要网络访问的应用程序。因为我将从我的服务器发出许多结构类似的请求,所以我创建了一个类来处理所有与网络相关的任务,因为我喜欢将事情划分开来。
我正在研究的一种方法是 createNetworkThread 从我的内心 NetworkManager 班级。此特定方法有三个参数: Context context, final String requestURI, final RequestBody formParameters 我需要的帮助是如何返回从这个方法接收到的数据,以便在调用中使用和操作它 Activity .
以下是所讨论的方法:

public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters) {
    if (!this.isConnected(context)) return;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(requestURI).post(formParameters).build();

            Response response = null;

            // Send login request, get response //

            try {
                response = client.newCall(request).execute();
                String stringResponse = response.body().string();
                JSONObject jsonResponse = new JSONObject(stringResponse);

                Log.d("Net", "Request send and received!");

            } catch (IOException e) {
                Log.d("Net", "Failed");
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(runnable);
    thread.start();
}

以下是活动的电话:

final NetworkManager Net = new NetworkManager(this);

...

final String requestURI = "http://192.168.1.111/videonow.club/apprequest/signup/thread.php";
final RequestBody formVars = new FormBody.Builder().add("email", strEmail).add("password", strPass1).add("first_name", strNameFirst).add("last_name", strNameLast).build();

Net.createNetworkThread(SignupActivity.this, requestURI, formVars);

我需要知道的是如何从 jsonResponse 从方法返回(我知道 void 不允许这样)这样我就可以使用数据了。
最好是 jsonObject 所以我可以用这样的东西:

SomeType response = Net.createNetworkThread(...);

或者,在 NetworkManager 它将由方法设置,以便调用和引用它,如下所示:

Net.createNetworkThread(...);
SomeType response = Net.someVariable;

还是有更合理的方法来接收这些数据?
我也在打电话 new OkHttpClient() 两次-一次在活动中,这样我就可以建立 requestBody post变量,以及 NetworkManager 类本身。我的直觉告诉我这是多余的。。。如果是的话,有没有办法提高效率?
提前谢谢!

khbbv19g

khbbv19g1#

您可以将okhttp与aysnctask一起使用,如下所示:

public class Webservice extends AsyncTask<String, String, UserResponse> {

private String TAG = Webservice.class.getSimpleName();
private static final String ENDPOINT = "YOUR_URL";
private static final Moshi MOSHI = new Moshi.Builder().build();
private static final JsonAdapter<UserResponse> CONTRIBUTORS_JSON_ADAPTER_RESPONSE = MOSHI.adapter(Types.newParameterizedType(UserResponse.class, UserResponse.class));

UserResponse webResponse;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String postBody = "postBody\n";

@Override
protected UserResponse doInBackground(String... parmas) {
    OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
    Call call = okHttpClient.build().newCall(new Request.Builder()
            .url(ENDPOINT)
            .post(RequestBody.create(JSON, postBody))
            .addHeader("Content-Type", "application/json")
            .build());

    try {
        Response response = call.execute();
        adModelResponse = CONTRIBUTORS_JSON_ADAPTER_RESPONSE.fromJson(response.body().source());

    } catch (IOException e) {
        e.printStackTrace();
    }
    return webResponse;
}

@Override
protected void onPostExecute(UserResponse adModelResponse) {

}
}

然后在活动中打电话如下:

Webservice webservice = new Webservice();
webservice.execute("YOUR_PARAMETER");

使用的库:
okhttp-3.2.0、moshi-1.1.0、okio-1.8.0

3okqufwl

3okqufwl2#

您可以使用回调接口将数据返回到活动中。考虑以下示例:

public interface JsonResponse {
   onResponseReceived(JSONObject response);
}

然后你的 createNetworkThread 威尔看起来像这样:

public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters, JsonResponse responseCallback) {
    if (!this.isConnected(context)) return;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(requestURI).post(formParameters).build();

            Response response = null;

            // Send login request, get response //

            try {
                response = client.newCall(request).execute();
                String stringResponse = response.body().string();
                JSONObject jsonResponse = new JSONObject(stringResponse);
                responseCallback.onResponseReceived(jsonResponse); // This line will return to your caller

                Log.d("Net", "Request send and received!");

            } catch (IOException e) {
                Log.d("Net", "Failed");
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(runnable);
    thread.start();
}

最后是来电者:

Net.createNetworkThread(SignupActivity.this, requestURI, formVars, new JsonResponse() {
            @Override
            public void onResponseReceived(JSONObject response) {
                // Do stuff in your activity
                // eventually use runOnUiThread for your UI operations 
            }
        });
bejyjqdl

bejyjqdl3#

使networkmanager抽象并添加一个抽象方法 public abstract void onResult(JSONObject response); 像这样重写这个方法

final NetworkManager Net = new NetworkManager(this){
@Override
public void onResult(JSONObject response){
//do whatever you want here
}
};

createNetworkThread 完成后,将此方法调用为

.....
response = client.newCall(request).execute();
                String stringResponse = response.body().string();
                JSONObject jsonResponse = new JSONObject(stringResponse);
onResult(jsonResponse);
......

相关问题