Android 请求http接口,sdk27,解析json
Post方式body带json的同步请求
导入依赖
implementation 'com.squareup.okhttp3:okhttp:3.8.1'
// gson解析的依赖
implementation 'com.google.code.gson:gson:2.8.0'
// Retrofit2的依赖
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
// gson解析的依赖
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
实现
try {
String json="{\n" +
"\t\t\t\"loginName\":\"st\",\n" +
"\t\t\t\"password\":\"j1\"\n" +
"\t\t\n" +
"\t\t\t}";
OkHttpClient client =new OkHttpClient();
Request request=new Request.Builder()
.url("http://www.yun.cn/wsjc/app/Login")
.post(RequestBody.create(MediaType.parse("application/json"),json))
.build();
Response response=client.newCall(request).execute();
String result =response.body().string();
result.toCharArray();
}
Post方式带参数的同步请求接口
try {
FormBody.Builder params=new FormBody.Builder();
params.add("username","lisi");
params.add("password","123456");
OkHttpClient client =new OkHttpClient();
Request request=new Request.Builder()
.url("http://172.81.240.47:8080/users/Login")
.post(params.build())
.build();
Response response=client.newCall(request).execute();
String result =response.body().string();
result.toCharArray();
}
Get方式同步请求接口
try {
OkHttpClient client =new OkHttpClient();
Request request=new Request.Builder()
.url("http://www.05n.cn/wsjc/Device/AppLogin.do?userID=jnst&userPassword=jn21")
.build();
Response response=client.newCall(request).execute();
String result =response.body().string();
result.toCharArray();
}
在Android请求http不能在主线程中
public void send_OnClick(View v)
{
Log.i("xx", "click send");
new Thread(new Runnable() {
@Override
public void run() {
try {
//调用接口
}
catch (Exception e)
{
e.printStackTrace();
}
}
}).start();
}
使用Gson解析json获取类对象
Step1导入依赖库
// gson解析的依赖
implementation ‘com.google.code.gson:gson:2.8.0’
// gson解析的依赖
implementation ‘com.squareup.retrofit2:converter-gson:2.3.0’
Step2
调试代码,根据请求成功获取的json串格式,通过在线,JSON生成Java实体类。在项目中新建java类,命名为xxxxBean.java 。
Step3使用Gson解析
Gson gson = new Gson();
LoginReceivedBean mLoginReceivedBean=gson.fromJson(result,LoginReceivedBean.class);
mLoginReceivedBean.toString();