我是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
获取JSON数据(我知道void
不允许这样做)所以我可以使用这些数据。
让jsonObject
返回会更好,所以我可以使用这样的东西:
SomeType response = Net.createNetworkThread(...);
或者,要在NetworkManager
中设置一个类变量,该类变量将由方法设置,因此它将被调用并引用如下:
Net.createNetworkThread(...);
SomeType response = Net.someVariable;
或者是否有更合理的方式来接收这些数据?
我也在调用new OkHttpClient()
两次 - 一次在活动中,因此我可以构建requestBody
帖子变量,以及NetworkManager
类本身。我的直觉告诉我这是多余的......如果是这样,有没有办法让这更有效率?
提前致谢!
答案 0 :(得分:0)
您可以将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) {
}
}
然后在这样的Activity调用中:
Webservice webservice = new Webservice();
webservice.execute("YOUR_PARAMETER");
使用的库:
okhttp-3.2.0,moshi-1.1.0,okio-1.8.0
答案 1 :(得分:0)
您可以使用回调界面将数据恢复到您的活动中。请考虑以下示例:
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
}
});
答案 2 :(得分:0)
创建NetworkManager Abstract并添加一个抽象方法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);
......