<uses-permission android:name="android.permission.INTERNET" />
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
}
package com.lxh.test.Uitls;
import android.os.Message;
import android.util.Log;
import com.lxh.test.activity.MainActivity2;
import com.lxh.test.mode.SD_class;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* create by lxh on 2023/4/21 Time:15:51
* tip:okhttp
*/
public class okHttpUtil {
private static final String TAG = "okHttpUtil lxh";
/**
* @param goto_url
* @param json_data
* @author create by lxh on 2023/4/23 14:24
* tip:okhttp POST 参数请求,参数格式application/json
*/
public static void OK_JSONPost(String goto_url, String json_data) {
MediaType JSON_type = MediaType.parse("application/json;charset=utf-8");
OkHttpClient okhttpclient1 = new OkHttpClient();
RequestBody requestBody = RequestBody.create(JSON_type, json_data);
Request request1 = new Request.Builder().url(goto_url).post(requestBody).build();
Call call = okhttpclient1.newCall(request1);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败的处理
Log.i(TAG, "Request failure " + "err=" + e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "Request successful " + "code=" + response.code() + ",data=" + response.toString());
if (response.code() == 200) {
String back_json = response.body().string();
Log.i(TAG, "Received data " + "back_json=" + back_json);
Message m = new Message();
m.what = 1;
m.obj = back_json;
MainActivity2.hander_receive.sendMessage(m);
}
}
});
}
/**
* @param goto_url
* @param sd_data
* @author create by lxh on 2023/4/23 14:24
* tip:okhttp POST 参数请求,参数格式x-www-form-urlencoded
*/
public static void OK_Post(String goto_url, SD_class sd_data) {
OkHttpClient okhttpclient1 = new OkHttpClient();
FormBody formBody = new FormBody.Builder()
.add("customerSn", sd_data.getCustomerSn())
.add("hardVersion", sd_data.getHardVersion())
.add("macAddr", sd_data.getMacAddr())
.add("productModel", sd_data.getProductModel())
.add("serialVersionUID", "0")
.add("sn", sd_data.getSn())
.add("softVersion", sd_data.getSoftVersion())
.build();
Request request1 = new Request.Builder()
.url(goto_url)
.post(formBody)
.build();
Call call = okhttpclient1.newCall(request1);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("lxh", "" + "url连接信息" + response.code()
+ "\n" + response.toString()
);
if (response.code() == 200) {
Message m = new Message();
m.what = 1;
m.obj = response.body().string();
MainActivity2.hander_receive.sendMessage(m);
}
}
});
}
}
package com.lxh.test.Uitls;
import android.content.Context;
import android.content.res.AssetManager;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class LocalJsonResolutionUtil {
public static String getJson(Context context, String fileName){
StringBuilder stringBuilder = new StringBuilder();
//获得assets资源管理器
AssetManager assetManager = context.getAssets();
//使用IO流读取json文件内容
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
assetManager.open(fileName),"utf-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
public static <T> T JsonToObject(String json, Class<T> type) {
Gson gson =new Gson();
return gson.fromJson(json, type);
}
}
package com.lxh.test.mode;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
/**
* create by lxh on 2023/4/21 Time:15:55
* tip:
*/
public class SD_class implements Serializable {
public SD_class(){}
//TEST
static String customerSn= "";
static String hardVersion= "";
static String macAddr= "";
static String productModel= "";
static int serialVersionUID= 0;
static String sn= "";
static String softVersion= "";
public static String GetSD_Base() {
JSONObject command = new JSONObject();
try {
command.put("customerSn", customerSn);
command.put("hardVersion", hardVersion);
command.put("macAddr", macAddr);
command.put("productModel", productModel);
command.put("serialVersionUID", serialVersionUID);
command.put("sn", sn);
command.put("softVersion", softVersion);
} catch (JSONException e) {
e.printStackTrace();
}
//String.valueOf(command)
return command.toString();
}
public String getCustomerSn() {
return customerSn;
}
public void setCustomerSn(String customerSn) {
this.customerSn = customerSn;
}
public String getHardVersion() {
return hardVersion;
}
public void setHardVersion(String hardVersion) {
this.hardVersion = hardVersion;
}
public String getMacAddr() {
return macAddr;
}
public void setMacAddr(String macAddr) {
this.macAddr = macAddr;
}
public String getProductModel() {
return productModel;
}
public void setProductModel(String productModel) {
this.productModel = productModel;
}
public int getSerialVersionUID() {
return serialVersionUID;
}
public void setSerialVersionUID(int serialVersionUID) {
this.serialVersionUID = serialVersionUID;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getSoftVersion() {
return softVersion;
}
public void setSoftVersion(String softVersion) {
this.softVersion = softVersion;
}
}
package com.lxh.test.mode;
/**
* create by lxh on 2023/4/21 Time:18:20
* tip:
*/
public class sdback_class {
String msg = "";
String fileName = "";
String code = "";
String url = "";
public sdback_class(){}
public sdback_class(String msg, String fileName, String code, String url) {
this.msg = msg;
this.fileName = fileName;
this.code = code;
this.url = url;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
package com.lxh.test.activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.lxh.test.R;
import com.lxh.test.Uitls.LocalJsonResolutionUtil;
import com.lxh.test.Uitls.SDUtil;
import com.lxh.test.Uitls.okHttpUtil;
import com.lxh.test.mode.SD_class;
import com.lxh.test.mode.sdback_class;
public class MainActivity2 extends AppCompatActivity {
public static Handler hander_receive;
private static final String TAG = "MainActivity2 lxh";
Handler hander = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what){
case 1:
String s2=msg.obj.toString();
sdback_class sdback_data = LocalJsonResolutionUtil.JsonToObject(s2, sdback_class.class);
Log.i(TAG," \ngetMsg="+ sdback_data.getMsg()
+ "\ngetCode="+ sdback_data.getCode()
+ "\ngetFileName="+ sdback_data.getFileName()
+"\ngetUrl="+ sdback_data.getUrl()
);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Log.i(TAG,"now in MainActivity2");
hander_receive=hander;
SD_class sd_data=new SD_class();
sd_data.setCustomerSn("new");
sd_data.setHardVersion("new");
sd_data.setMacAddr("new");
sd_data.setProductModel("new");
sd_data.setSerialVersionUID(0);
sd_data.setSn("new");
sd_data.setSoftVersion("new");
okHttpUtil.OK_JSONPost(SDUtil.sdurl,SD_class.GetSD_Base());
}
}
I/MainActivity2 lxh: now in MainActivity2
I/okHttpUtil lxh: Request successful code=200,data=Response{protocol=http/1.1, code=200, message=, url=http://xx.xxx.xx.xx:xxxx/xx/xx}
I/okHttpUtil lxh: Received data back_json={"msg":"操作成功","fileName":"测试","code":200,"url":"http://xx.xxx.xx.xx:xxxx/common/xx/xx"}
I/MainActivity2 lxh:
getMsg=操作成功
getCode=200
getFileName=测试
getUrl=http://xx.xxx.xx.xx:xxxx/common/xx/xx
response.body().string()只能使用一次。
封装内容有参考此文章: Okhttp的GET与POST使用、MIME、常见问题及拦截器
package com.lxh.test.Uitls;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* create by lxh on 2023/4/23 Time:10:53
* tip:okhttp封装类
*/
public class OKHttpSeal {
private static final String TAG = "OKHttpSeal lxh";
private static OKHttpSeal mInstance;
private OkHttpClient mOkhttpClient;
private Handler mHandler;
/**
* 给外部暴露调用
* DCL机制:解决多线程并发问题
*
* @param context
*/
public static OKHttpSeal getInsatnce(Context context) {
if (mInstance == null) {
synchronized (OKHttpSeal.class) {
if (mInstance == null) {
mInstance = new OKHttpSeal(context);
}
}
}
return mInstance;
}
private OKHttpSeal(Context context) {
File sdcache = context.getExternalCacheDir();
int cacheSize = 10 * 1024 * 1024;
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
mOkhttpClient = builder.build();
mHandler = new Handler();
}
/**
* 以异步POST请求为例
*/
public void OK_JSONPost(String goto_url, String json_data, OKResultCallback okcallback) {
MediaType JSON_type = MediaType.parse("application/json;charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON_type, json_data);
Request request1 = new Request.Builder()
.url(goto_url)
.post(requestBody)
.build();
Call call = mOkhttpClient.newCall(request1);
dealResult(call, okcallback);//处理结果
}
/**
* 以异步GET请求为例
*/
public void getAsyncHttp(String goto_url, OKResultCallback okcallback) {
final Request request = new Request.Builder()
.url(goto_url)
.build();
Call call = mOkhttpClient.newCall(request);
dealResult(call, okcallback);//处理结果
}
private void dealResult(Call call, final OKResultCallback callback) {
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "Request failure " + "err=" + e.toString());
sendFailedCallback(call.request(), e, callback);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "Request successful " + "code=" + response.code() + ",data=" + response.toString());
sendSuccessCallback(response, callback);
// if (response.code() == 200) {
// Log.i(TAG, "Received data " + "BACK_json=" + response.body().string());
// }else{}
}
});
}
private void sendSuccessCallback(final Response response, final OKResultCallback callback) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (callback != null) {
try {
callback.onResponse(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
private void sendFailedCallback(final Request request, final IOException e, final OKResultCallback callback) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (callback != null) {
callback.onError(request, e);
}
}
});
}
}
package com.lxh.test.Uitls;
import java.io.IOException;
import okhttp3.Request;
import okhttp3.Response;
/**
* create by lxh on 2023/4/23 Time:11:00
* tip:
*/
public abstract class OKResultCallback {
public abstract void onError(Request request, Exception e);
public abstract void onResponse(Response response) throws IOException;
}
OKHttpSeal.getInsatnce(MainActivity2.this).OK_JSONPost(okHttpUtil.sdurl, SD_class.GetSD_Base(),new OKResultCallback() {
@Override
public void onError(Request request, Exception e) {
}
@Override
public void onResponse(Response response) throws IOException {
if (response.code() == 200) {
String back_json = response.body().string();
Log.i(TAG, "Received data " + "back_json=" + back_json);
Message m = new Message();
m.what = 1;
m.obj = back_json;
hander_receive.sendMessage(m);
}
}
});
连续使用有response.body().string()的问题。