android 访问rest api的封装方法
调用方法:
@Override
public void onClick(View v) {
if(v.getId()==R.id.btn_login)
{
//get 调用方法
String get_rest_api_url="http://121.42.242.230:9999/api/user/getUserByID/1";
webTool.get(get_rest_api_url, new CallbackData<ResultData>(){
@Override
public void call(ResultData r) {
System.out.println(r.isOK);
if(r.data!=null) {
JSONObject jObj=(JSONObject)r.data;
System.out.println("userId="+webTool.getValue(jObj,"userId"));
System.out.println("userName="+webTool.getValue(jObj,"userName"));
System.out.println(r.data.toString());
}
}
} );
//post 调用方法
String post_rest_api_url="http://121.42.242.230:9999/api/user/login";
Map<String, Object> paramterMap = new HashMap<>();
paramterMap.put("username","admin");
paramterMap.put("password","admin");
paramterMap.put("rememberMe",true);
webTool.post(post_rest_api_url,paramterMap, new CallbackData<ResultData>(){
@Override
public void call(ResultData r) {
System.out.println(r.isOK);
if(r.data!=null) {
JSONObject jObj=(JSONObject)r.data;
System.out.println("post userId="+webTool.getValue(jObj,"userId"));
System.out.println("post userName="+webTool.getValue(jObj,"userName"));
System.out.println(r.data.toString());
}
}
} );
//dbHelper dbHelper=new dbHelper(this,"cwgis.db");
//String sql="create table user(id varchar(40),name text,pwd text)";
//dbHelper.execSQL(sql);
//跳转到webView页面
Intent web_intent=new Intent(MainActivity.this,activity_web.class);
startActivity(web_intent);
MainActivity.this.finish();
//跳转到Help页面
/*
Intent help_intent = new Intent(MainActivity.this, HelpActivity.class);
startActivity(help_intent);
MainActivity.this.finish();
*/
}
}
webtool工具定义:
package com.cwgis.demo.common;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cwgis.demo.objects.CallbackData;
import com.cwgis.demo.objects.ResultData;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class webTool {
private static OkHttpClient client=null;
static{
client = new OkHttpClient.Builder()
.connectTimeout(500, TimeUnit.SECONDS)
.writeTimeout(500, TimeUnit.SECONDS)
.readTimeout(500, TimeUnit.SECONDS)
.build();
}
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = manager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
//同步get test
public void test_get_tb() throws Exception{
Request r=new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Response rp=client.newCall(r).execute();
if(rp.isSuccessful()==false) throw new IOException("unExpected code "+rp);
Headers rpHeaders=rp.headers();
for(int i=0;i<rpHeaders.size();i++)
{
System.out.println(rpHeaders.name(i)+":"+rpHeaders.value(i));
}
System.out.println(rp.body().string());
}
//异步get test
public void test_get_await()
{
Request r=new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(r).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response rp) throws IOException {
if(rp.isSuccessful()==false) throw new IOException("unExpected code "+rp);
Headers rpHeaders=rp.headers();
for(int i=0;i<rpHeaders.size();i++)
{
System.out.println(rpHeaders.name(i)+":"+rpHeaders.value(i));
}
System.out.println(rp.body().string());
}
});
}
//---------------------------------
public static String toJSON(Object obj) {
String json = JSONObject.toJSONString(obj, SerializerFeature.WriteMapNullValue);
return json;
}
public static String getValue(JSONObject jObj,String key)
{
String rbc="";
try {
if (jObj != null) {
rbc = jObj.getString(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
public static Boolean getValueBoolean(JSONObject jObj,String key)
{
Boolean rbc=false;
try {
if (jObj != null) {
rbc = jObj.getBoolean(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
public static Double getValueDouble(JSONObject jObj,String key)
{
Double rbc=0.0;
try {
if (jObj != null) {
rbc = jObj.getDouble(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
public static double getValueDouble2(JSONObject jObj,String key)
{
double rbc=0.0;
try {
if (jObj != null) {
rbc = jObj.getDoubleValue(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
public static Float getValueFloat(JSONObject jObj, String key)
{
Float rbc=0.0f;
try {
if (jObj != null) {
rbc = jObj.getFloat(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
public static float getValueFloat2(JSONObject jObj, String key)
{
float rbc=0.0f;
try {
if (jObj != null) {
rbc = jObj.getFloatValue(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
public static Integer getValueInteger(JSONObject jObj,String key)
{
Integer rbc=0;
try {
if (jObj != null) {
rbc = jObj.getInteger(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
public static int getValueInt(JSONObject jObj,String key)
{
int rbc=0;
try {
if (jObj != null) {
rbc = jObj.getIntValue(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
public static Date getValueDate(JSONObject jObj, String key)
{
Date rbc=null;
try {
if (jObj != null) {
rbc = jObj.getDate(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
public static byte[] getValueBytes(JSONObject jObj, String key)
{
byte[] rbc=null;
try {
if (jObj != null) {
rbc = jObj.getBytes(key);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return rbc;
}
//---------------------------------
//下载文件保存到文件为savePath路径的地方
public static boolean savePhoto(String savePath, Response response) {
// savePath = AndroidTool.getMainActivity().getFilesDir()+"/123.jpg";
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
// 储存下载文件的目录
FileTool.exitsDir(FileTool.getDir(savePath), true);
//
is = response.body().byteStream();
File file = new File(savePath);
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
return false;
}
}
return true;
}
//---------------------------------
//抽象get调用方法
public static void ajax(Request request, CallbackData<ResultData> r) {
client.newCall(request).enqueue(new Callback() {
//请求失败
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
ResultData rd=new ResultData();
rd.isOK=false;
rd.msg=e.getMessage();
r.call(rd);
}
//有响应
@Override
public void onResponse(Call call, Response response) throws IOException {
ResultData rd=new ResultData();
if (!response.isSuccessful()) {
//请求失败
rd.isOK=false;
rd.msg="连接服务器失败";
r.call(rd);
return;
}
String data = response.body().string();
rd = JSON.parseObject(data, ResultData.class);
rd.response=response;
//
r.call(rd);
}
});
}
public static void get(String rest_api_url,CallbackData<ResultData> r_callback)
{
Request r=new Request.Builder()
.url(rest_api_url)
.build();
ajax(r, new CallbackData<ResultData>() {
@Override
public void call(ResultData rd) {
r_callback.call(rd);
/*
if(rd.isOK==true)
{
System.out.println("good");
}
else
{
System.out.println("no");
}*/
}
});
}
// post调用法
public static void post(String rest_api_url, Map<String, Object> paramterMap, CallbackData<ResultData> r_callback)
{
FormBody.Builder bodyBuild = new FormBody.Builder();
//formBodyBuilderAdd(formBodyBuilder);
//Map paramterMap = new HashMap<>();
//Map fileMap = new HashMap<>();
//添加传入的参数
for (String key : paramterMap.keySet()) {
Object obj = paramterMap.get(key);
if (obj instanceof String) {
bodyBuild.add(key, (String) obj);
} else {
bodyBuild.add(key, webTool.toJSON(obj));
}
}
FormBody formBody = bodyBuild.build();
Request request = new Request
.Builder()
.addHeader("Content-Type", "application/json")
.post(formBody)
.url(rest_api_url)
.build();
ajax(request,new CallbackData<ResultData>() {
@Override
public void call(ResultData rd) {
r_callback.call(rd);
}
});
}
public static void post_File(String rest_api_url, Map<String, Object> paramterMap, Map<String, File> fileMap, CallbackData<ResultData> r_callback)
{
MultipartBody.Builder bodyBuild = new MultipartBody.Builder();
//formBodyBuilderAdd(bodyBuild);
//添加传入的参数
MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
for (String key : paramterMap.keySet()) {
Object obj = paramterMap.get(key);
if (obj instanceof String) {
bodyBuild.addFormDataPart(key, (String) obj);
} else {
bodyBuild.addFormDataPart(key, webTool.toJSON(obj));
}
}
for (String key : fileMap.keySet()) {
File file = fileMap.get(key);
bodyBuild.addFormDataPart("path", file.getAbsolutePath(), RequestBody.create(MEDIA_TYPE_MARKDOWN, file));
}
Request request = new Request.Builder()
.url(rest_api_url)
.post(bodyBuild.build())
.build();
ajax(request,new CallbackData<ResultData>() {
@Override
public void call(ResultData rd) {
r_callback.call(rd);
}
});
}
//---------------------------------
}
ResultData类定义:
package com.cwgis.demo.objects;
import java.io.Serializable;
import okhttp3.Response;
public class ResultData implements Serializable {
public boolean isOK=false;
public Object data=null;
public String msg="";
public String code="";
//
public Response response=null;
}
CallbackData接口定义:
package com.cwgis.demo.objects;
public interface CallbackData<T> {
void call(T t);
}
AndroidManifest.xml文件权限设置
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cwgis.demo">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera2.full" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".activity_web"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".views.HelpActivity">
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle文件引入的第三方库:
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.cwgis.demo"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.alibaba:fastjson:1.1.54.android'
implementation 'com.squareup.okhttp3:okhttp:4.7.2'
implementation 'com.squareup.okio:okio:1.12.0'
implementation files('libs/ocr-sdk.jar')
implementation files('libs/tiandituapi3.0.jar')
}
主要是下面这几个第三方库:
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.alibaba:fastjson:1.1.54.android'
implementation 'com.squareup.okhttp3:okhttp:4.7.2'
implementation 'com.squareup.okio:okio:1.12.0'
问题说明:
在添加了新权限后,要在模拟器中卸载开发的app,重新安装后权限才有效。
----the----end------