Commit 0f23a161 by gao.chao

网络访问基本模板

parent 44a8a434
......@@ -5,9 +5,14 @@ import android.support.annotation.Nullable;
import android.view.View;
import com.mayi.fastdevelop.base.BaseActivity;
import com.mayi.fastdevelop.bean.UserInfo;
import com.mayi.fastdevelop.comnon.Constant;
import com.mayi.fastdevelop.okhttp.NetWorkBuilder;
import com.mayi.fastdevelop.okhttp.NetWorkUtil;
import com.mayi.fastdevelop.okhttp.ResultCallback;
import com.mayi.fastdevelop.view.OnMultiClickListener;
public class FunctionActivity extends BaseActivity{
public class FunctionActivity extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
......@@ -43,6 +48,44 @@ public class FunctionActivity extends BaseActivity{
gotoActivity(FragmentInteractiveActivity2.class);
}
});
findViewById(R.id.b6).setOnClickListener(new OnMultiClickListener() {
@Override
public void onMultiClick(View v) {
new NetWorkBuilder().setUrl("https://customer.kujiatech.com/api/thirdPartyService/notify/getNotify")
.addParam("1", "22")
.setMethod(Constant.NETWORK_METHOD_GET)
.setCallback(new ResultCallback<UserInfo>() {
@Override
public void onFail(String msg) {
showToast(msg);
}
@Override
public void onSuccess(UserInfo o) {
showToast(o.toString());
}
}).execute();
}
});
findViewById(R.id.b7).setOnClickListener(new OnMultiClickListener() {
@Override
public void onMultiClick(View v) {
new NetWorkBuilder().setUrl("https://customer.kujiatech.com/api/thirdPartyService/notify/getNotify")
.addParam("1", "22")
.setCallback(new ResultCallback<UserInfo>() {
@Override
public void onFail(String msg) {
showToast(msg);
}
@Override
public void onSuccess(UserInfo o) {
showToast(o.toString());
}
}).execute();
}
});
}
......
......@@ -54,7 +54,7 @@ public class MainActivity extends BaseActivity {
public void onBindViewHolder(@NonNull MyViewHolder viewHolder, int i) {
viewHolder.tv.setOnClickListener(list.get(i).getClickListener());
viewHolder.tv.setText(list.get(i).getText());
DrawableUtils.setStatePressedDrawable(viewHolder.tv,"#555555","#F00000","#999999");
DrawableUtils.setStatePressedDrawable(viewHolder.tv, "#555555", "#F00000", "#999999");
}
@Override
......
......@@ -38,6 +38,18 @@
android:layout_height="wrap_content"
android:text="Activity与Fragment之间交互\n不可以左右滑动" />
<Button
android:id="@+id/b6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发起get请求" />
<Button
android:id="@+id/b7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发起post请求" />
</LinearLayout>
......
......@@ -2,6 +2,9 @@ package com.mayi.fastdevelop.comnon;
public class Constant {
public static final String NETWORK_METHOD_POST="post";//发起post请求
public static final String NETWORK_METHOD_GET="get";//发起get请求
public static final String ACTIVITY_TAG="Activity";
}
package com.mayi.fastdevelop.okhttp;
import android.text.TextUtils;
import com.mayi.fastdevelop.comnon.Constant;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class NetWorkBuilder {
private String method = Constant.NETWORK_METHOD_POST; //发起请求方式get/post
private String url;
private Map<String, String> headers = new HashMap<>();
private ResultCallback callback;
private JSONObject params = new JSONObject();
private String stringParam;
public void setStringParam(String stringParam) {
this.stringParam = stringParam;
}
public NetWorkBuilder setCallback(ResultCallback callback) {
this.callback = callback;
return this;
}
public NetWorkBuilder setMethod(String method) {
this.method = method;
return this;
}
public NetWorkBuilder setUrl(String url) {
this.url = url;
return this;
}
public NetWorkBuilder addHeader(String key, String header) {
headers.put(key, header);
return this;
}
public NetWorkBuilder addParam(String key, String param) {
try {
params.put(key, param);
} catch (JSONException e) {
e.printStackTrace();
}
return this;
}
public void execute() {
if (TextUtils.isEmpty(url)) {
return;
}
if (TextUtils.equals(method, Constant.NETWORK_METHOD_GET)) {
sendGet();
} else if (TextUtils.equals(method, Constant.NETWORK_METHOD_POST)) {
sendPost();
}
}
//发起post请求
private void sendPost() {
if (!TextUtils.isEmpty(stringParam)) {
NetWorkUtil.getInstance().performSynPostHttpRequest(url, stringParam, callback);
} else if (params.toString().length() > 2) {
StringBuilder builder = new StringBuilder();
builder.append("?");
Iterator<String> keys = params.keys();
while (keys.hasNext()) {
String key = keys.next().toString();
String value = params.optString(key);
builder.append(key);
builder.append("=");
builder.append(value);
builder.append("&");
}
String s = builder.toString();
s.substring(0, s.length() - 1);
NetWorkUtil.getInstance().performSynPostHttpRequest(url, params.toString(), callback);
} else {
NetWorkUtil.getInstance().performSynPostHttpRequest(url, null, callback);
}
}
//发起get请求
private void sendGet() {
if (!TextUtils.isEmpty(stringParam)) {
NetWorkUtil.getInstance().performSynGetHttpRequest(url + "?" + stringParam, callback);
} else if (params.toString().length() > 2) {
StringBuilder builder = new StringBuilder();
builder.append("?");
Iterator<String> keys = params.keys();
while (keys.hasNext()) {
String key = keys.next().toString();
String value = params.optString(key);
builder.append(key);
builder.append("=");
builder.append(value);
builder.append("&");
}
String s = builder.toString();
s.substring(0, s.length() - 1);
NetWorkUtil.getInstance().performSynGetHttpRequest(url + s, callback);
} else {
NetWorkUtil.getInstance().performSynGetHttpRequest(url, callback);
}
}
}
package com.mayi.fastdevelop.okhttp;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import com.alibaba.fastjson.JSON;
import com.mayi.fastdevelop.bean.UserInfo;
import com.mayi.fastdevelop.util.LogUtils;
import com.orhanobut.logger.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
public class NetWorkUtil {
private static NetWorkUtil instance;
private OkHttpClient client;
private final MediaType FORM_CONTENT_TYPE
= MediaType.parse("application/json;charset=utf-8");
private Handler handler;
private NetWorkUtil() {
client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS).build();
handler = new Handler(Looper.getMainLooper());
}
public static NetWorkUtil getInstance() {
if (instance == null) {
instance = new NetWorkUtil();
}
return instance;
}
/**
* 将InputStream转换为String
*
* @param is
* @return
*/
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "/n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String str = sb.toString();
str = str.substring(0, str.length() - 2);
return str;
}
// 上传文件
// public String uploadFile(String url, File file) {
// try {
// String result = "";
// MediaType FROM_DATA = MediaType.parse("multipart/form-data");
// RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
// MultipartBody body = new MultipartBody.Builder().setType(FROM_DATA).addFormDataPart("file", "SoundRecording.wav", fileBody).build();
//
// //构建请求
// Request request = new Request.Builder()
// .post(body)//添加请求体
// .url(url)
// .build();
// Response response = client.newCall(request).execute();
// if (response.isSuccessful()) {
// result = convertStreamToString(response.body().byteStream());
// }
// Logger.i("url=" + url);
// Logger.i("result=" + result);
// return result;
// } catch (IOException e) {
// e.printStackTrace();
// Logger.i("url=" + url);
// if (TextUtils.isEmpty(e.getMessage())) {
// Logger.i("Exception Message is null");
// } else {
// Logger.i("Exception=" + e.getMessage());
// }
// return "";
// }
// }
//发起get请求
public void performSynGetHttpRequest(String url, ResultCallback callback) {
Request request = new Request.Builder()
.url(url)
.build();
initiateRequest(callback, request);
}
private void initiateRequest(final ResultCallback callback, Request request) {
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (callback != null) {
handler.post(new Runnable() {
@Override
public void run() {
if (e instanceof UnknownHostException) {
callback.onFail("连接网络异常");
} else {
callback.onFail("服务器繁忙,请稍后再试!");
}
}
});
}
LogUtils.netWorkFail("NetWorkUtil", call.request().url().toString(), bodyToString(call.request()), e);
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
//{"code":401,"msg":"UNAUTHORIZED","ok":false,"timestamp":1551166509635,"obj":"网络成功返回数据"}
final String json = convertStreamToString(response.body().byteStream());
if (callback != null) {
try {
final JSONObject jsonObject = new JSONObject(json);
boolean ok = jsonObject.optBoolean("ok");
if (ok) {
handler.post(new Runnable() {
@Override
public void run() {
callback.onSuccess(JSON.parseObject(jsonObject.optString("data")
, callback.getGenericType(0)));
}
});
} else {
handler.post(new Runnable() {
@Override
public void run() {
callback.onFail(jsonObject.optString("msg", "服务器繁忙,请稍后再试!"));
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
LogUtils.netWorkSuccess("NetWorkUtil", call.request().url().toString(), bodyToString(call.request()), json);
}
});
}
//发起post请求
public void performSynPostHttpRequest(String url, String json, ResultCallback callback) {
if (TextUtils.isEmpty(json)) {
json = "";
}
RequestBody body = RequestBody.create(FORM_CONTENT_TYPE, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
initiateRequest(callback, request);
}
private boolean isText(MediaType mediaType) {
if (mediaType.type() != null && mediaType.type().equals("text")) {
return true;
}
if (mediaType.subtype() != null) {
if (mediaType.subtype().equals("json") ||
mediaType.subtype().equals("xml") ||
mediaType.subtype().equals("html") ||
mediaType.subtype().equals("webviewhtml")
)
return true;
}
return false;
}
private String bodyToString(Request request) {
RequestBody requestBody = request.body();
if (requestBody != null) {
MediaType mediaType = requestBody.contentType();
if (mediaType != null) {
if (isText(mediaType)) {
try {
Request copy = request.newBuilder().build();
Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "something error when show requestBody.";
}
} else {
return "requestBody's content : maybe [file part] , too large too print , ignored!";
}
}
}
return "";
}
}
package com.mayi.fastdevelop.okhttp;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public abstract class ResultCallback<T> {
public abstract void onFail(String msg);
public abstract void onSuccess(T t);
/**
* 泛型具体实体Tyle
*
* @param index
* @return
*/
public Type getGenericType(int index) {
Type genType = getClass().getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
throw new RuntimeException("Index outof bounds");
}
return params[index];
}
}
......@@ -20,7 +20,7 @@ public class LogUtils {
*/
public static void postCatchedException(Exception e) {
StringBuffer msg = new StringBuffer();
if (!TextUtils.isEmpty(TAG)){
if (!TextUtils.isEmpty(TAG)) {
msg.append(TAG);
msg.append("--");
}
......@@ -63,9 +63,9 @@ public class LogUtils {
* @param parameter
* @param result
*/
public static void netWorkSuccess(String tag, String url, Object parameter, Object result) {
public static void netWorkSuccess(String tag, String url, String parameter, String result) {
Logger.i(tag + " netWork Success url=" + url + " parameter=" +
JSON.toJSONString(parameter) + " result=" + JSON.toJSONString(result));
parameter + " result=" + result);
}
/**
......@@ -76,10 +76,10 @@ public class LogUtils {
* @param parameter
* @param e
*/
public static void netWorkFail(String tag, String url, Object parameter, Exception e) {
public static void netWorkFail(String tag, String url, String parameter, Exception e) {
postCatchedException(e);
Logger.i(tag + " netWork Fail url=" + url + " parameter=" +
JSON.toJSONString(parameter) + " Exception=" + e.toString());
parameter + " Exception=" + e.toString());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment