最近开发某个Android项目:DateListThingsAnalyse-Android,其中用到了Fragment来展示数据,获取数据一直被卡住了。最后在StackOverflow找到了相关解决办法。建议还是去clone一下我的项目查看实际代码去体会用法。
okhttp工具类
-
这里POST和GET方法都有
public class Singleton {
private static Singleton INSTANCE = null;
private Singleton() {};
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.get("application/json; charset=utf-8");
public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}
public void doGetRequest(String url, final HttpResponseCallBack responseCallBack) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String strResponse = response.body().string();
Log.v("getStream-strResponse",strResponse);
try {
responseCallBack.getResponse(strResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void doPostRequest(String url,String json, final HttpResponseCallBack responseCallBack) throws IOException {
RequestBody body = RequestBody.create(json, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String strResponse = response.body().string();
Log.v("getStream-strResponse",strResponse);
try {
responseCallBack.getResponse(strResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
接口
package info.emperinter.DateListThingsAnalyseAndroid.API;
import org.json.JSONException;
public interface HttpResponseCallBack {
void getResponse(String response) throws JSONException;
}
fragment
如需了解更多,请访问:https://www.emperinter.info/2022/02/14/how-to-get-data-from-okhttp-in-fragment/