new Thread() {
@Override
public void run() {
OkHttpClient client = new OkHttpClient();
//user=xwl&age=99&size18
FormBody form = new FormBody.Builder()
.add("user", dataMap.get("username"))
.add("pwd", dataMap.get("password"))
.add("sign", dataMap.get("sign")).build();
Request req = new Request.Builder().url("http://192.168.0.6:9999/login").post(form).build();
Call call = client.newCall(req);
try {
Response res = call.execute();
ResponseBody body = res.body();
// 字符串={"status": true, "token": "fffk91234ksdujsdsd", "name": "xwl"}
String dataString = body.string();
// Log.e("MDS", "请求成功获取返回值=" + dataString);
} catch (IOException ex) {
Log.e("MDS", "网络请求错误");
}
}
}.start();
- json格式
new Thread() {
@Override
public void run() {
OkHttpClient client = new OkHttpClient();
// dataMap = {"username":"xwl","password":"123","sign":"用户名和密码的md5值"}
JSONObject json = new JSONObject(dataMap);
String jsonString = json.toString();
// RequestBody form = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),jsonString);
RequestBody form = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),jsonString);
Request req = new Request.Builder().url("http://192.168.0.6:9999/login").post(form).build();
Call call = client.newCall(req);
try {
Response res = call.execute();
ResponseBody body = res.body();
String dataString = body.string();
Log.i("登录", dataString);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
- 请求拦截器
- 假设开发app,发送10个请求,每个请求中需要携带特殊的请求头:xxxx。如是开发会将所有请求公共的操作都放在拦截器里面。
// 创建拦截器
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
// 1988812212 + 固定字符串 => md5加密
Request request = chain.request().newBuilder().addHeader("ts", "1988812212").addHeader("sign", "xxxx").build();
// 请求前
Response response = chain.proceed(request);
// 请求后
return response;
}
};
new Thread() {
@Override
public void run() {
// 线程执行的内容
// user=xxx&pwd=xxx&sign=xxxx
// OkHttpClient client = new OkHttpClient.Builder().build();
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build(); //添加拦截器
FormBody form = new FormBody.Builder()
.add("user", dataMap.get("username"))
.add("pwd", dataMap.get("password"))
.add("sign", dataMap.get("sign")).build();
Request req = new Request.Builder().url("http://192.168.0.6:9999/login").post(form).build();
Call call = client.newCall(req);
try {
Response res = call.execute();
ResponseBody body = res.body();
String dataString = body.string();
Log.e("请求发送成功", dataString);
} catch (IOException ex) {
Log.e("Main", "网络请求异常");
}
}
}.start();
- 基于retrofit
- 内部封装了okhttp,让你用的更加的简单
- 接口声明网络请求
public interface HttpReq {
// 向/api/v1/post 发送POST请求 name=xx&pwd=xxx
@POST("/api/v1/post")
@FormUrlEncoded
Call<ResponseBody> postLogin(@Field("name") String userName, @Field("pwd") String password);
// ->/api/v2/xxx?age=999
@GET("/api/v2/xxx")
Call<ResponseBody> getInfo(@Query("age") String age);
// 向/post/users 发送POST请求 {name:xxxx,age:123}
@POST("/post/users")
Call<ResponseBody> postLoginJson(@Body RequestBody body);
@GET("/index")
Call<ResponseBody> getIndex(@Query("age") String age);
}
- 发送请求
//表单格式
new Thread() {
@Override
public void run() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
HttpRequest httpRequest = retrofit.create(HttpRequest.class);
// https://www.httpbin.org/api/v1/post
// name=xx&pwd=xxx
Call<ResponseBody> call = httpRequest.postLogin("wupeiqi", "666");
try {
ResponseBody responseBody = call.execute().body();
String responseString = responseBody.string();
Log.i("登录", responseString);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
//json格式
new Thread() {
@Override
public void run() {
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
HttpRequest httpRequest = retrofit.create(HttpRequest.class);
JSONObject json = new JSONObject(dataMap);
String jsonString = json.toString();
RequestBody form = RequestBody.create(MediaType.parse("application/json;charset=utf-8"),jsonString);
// https://www.httpbin.org/post/users
// {username:"root",password:"123","sign":"xxxxdfsdfsdfsdfdfd"}
Call<ResponseBody> call = httpRequest.postLoginJson(form);
try {
ResponseBody responseBody = call.execute().body();
String responseString = responseBody.string();
Log.i("登录", responseString);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
- 2.序列化与反序列化
- Gson组件,implementation 'com.google.code.gson:gson:2.8.6'
//2.1序列化,对象--->>字符串
class HttpContext{
public int code;
public String message;
public HttpContext(int code,String msg){
this.code = code;
this.message = msg;
}
}
HttpContext obj = new HttpContext(1000,"成功");
# json.dumps
String dataString = new Gson().toJson(obj); // '{"code":1000,"Message":"成功"}'
//2.2反序列化,字符串 -> 对象
// JSON格式
String dataString = "{\"status\": true, \"token\": \"fffk91234ksd\", \"name\": \"xwl\"}";
class HttpResponse{
public boolean status;
public String token;
public String name;
}
HttpResponse obj = new Gson().fromJson(dataString,HttpResponse.class);
obj.status
obj.name
obj.token
- 3.保存到xml文件
- 手机上APP产生数据的路径:/data/data/包名/...
- 手机上APP安装包的位置:/data/app/包名
- 有时候,APP启动或者运行过程中会保存一些数据到特殊的xml文件中,方便后续读取或者权限检测。 /data/data/com.nb.ss/shared_prefs/sp_city.xml
//保存
SharedPreferences sp = getSharedPreferences("sp_city", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("token","111111");
editor.commit();
//删除
SharedPreferences sp = getSharedPreferences("sp_city", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove("token");
editor.commit();
//获取
SharedPreferences sp = getSharedPreferences("sp_city", MODE_PRIVATE);
String token = sp.getString("token","");