Commit f5333e58 authored by 张释方's avatar 张释方

添加百度api服务

parent 357011e5
package com.mints.street.api
import com.google.gson.JsonObject
import com.mints.street.bean.BaseResponse
import com.mints.street.netwrok.baidu.BaiduHttpManager
import io.reactivex.Observable
import retrofit2.Response
import retrofit2.http.*
interface BaiduApi {
companion object {
var BAIDU_IP = "http://api.map.baidu.com/"
fun newInstance(): BaiduApi {
return BaiduHttpManager.getInstance().defaultClient.create(BaiduApi::class.java)
}
}
/**
* 国内
*
* @return
*/
@GET("place/v2/suggestion")
fun suggestionPlace(@Body vo: @JvmSuppressWildcards Map<String, Any>): Observable<Response<BaseResponse<Any>>>
/**
* 国外
*
*
* vo["region"] = "全球"
vo["output"] = "json"
vo["ak"] = "tnFhCM9cTeTDZqNjRPVHbfzOz6AUPoEq"@return
*/
@GET("place_abroad/v1/suggestion")
// fun suggestionPlaceAbroad(@Query vo: @JvmSuppressWildcards Map<String, Any>): Observable<Response<BaseResponse<Any>>>
fun suggestionPlaceAbroad(@Query("query") vo: String,@Query("region") vo2: String,
@Query("output") vo3: String,@Query("ak") vo4: String): Observable<Response<BaseResponse<Any>>>
}
\ No newline at end of file
...@@ -111,6 +111,7 @@ class MyFragment : BaseFragment<FragmentMyBinding, MyViewModel>(), OnRefreshList ...@@ -111,6 +111,7 @@ class MyFragment : BaseFragment<FragmentMyBinding, MyViewModel>(), OnRefreshList
RxUtils.onMultiClick(aboutus) { RxUtils.onMultiClick(aboutus) {
startActivity(AboutusActivity::class.java) startActivity(AboutusActivity::class.java)
// viewModel.test()
} }
RxUtils.onMultiClick(moresettings) { RxUtils.onMultiClick(moresettings) {
startActivity(MoresettingsActivity::class.java) startActivity(MoresettingsActivity::class.java)
......
...@@ -8,6 +8,7 @@ import com.mints.street.common.DeviceInfo ...@@ -8,6 +8,7 @@ import com.mints.street.common.DeviceInfo
import com.mints.street.manager.UserManager import com.mints.street.manager.UserManager
import com.mints.street.manager.oaid.OaidManager import com.mints.street.manager.oaid.OaidManager
import com.mints.street.model.ApiModel import com.mints.street.model.ApiModel
import com.mints.street.model.BaiduModel
import com.mints.street.netwrok.base.HttpSubscribeImpl import com.mints.street.netwrok.base.HttpSubscribeImpl
import com.mints.street.utils.DeviceUuidFactory import com.mints.street.utils.DeviceUuidFactory
import me.goldze.mvvmhabit.base.BaseViewModel import me.goldze.mvvmhabit.base.BaseViewModel
...@@ -101,4 +102,31 @@ class MyViewModel(application: Application) : BaseViewModel(application) { ...@@ -101,4 +102,31 @@ class MyViewModel(application: Application) : BaseViewModel(application) {
}) })
} }
/**
* 获取个人信息
*/
fun test() {
val vo = hashMapOf<String, Any>()
vo["query"] = "澳大利亚 海岸"
vo["region"] = "全球"
vo["output"] = "json"
vo["ak"] = "tnFhCM9cTeTDZqNjRPVHbfzOz6AUPoEq"
// BaiduModel.suggestionPlaceAbroad(lifecycleProvider,vo).safeSubscribe(
BaiduModel.suggestionPlaceAbroad(lifecycleProvider,"澳大利亚 海岸","全球","json","tnFhCM9cTeTDZqNjRPVHbfzOz6AUPoEq").safeSubscribe(
object : HttpSubscribeImpl<BaseResponse<Any>>(
this@MyViewModel, true) {
override fun onBusinessSuccess(response: BaseResponse<Any>) {
println("mcg __ "+response.result)
}
override fun onError(e: Throwable) {
}
}
)
}
} }
\ No newline at end of file
package com.mints.street.model
import com.google.gson.JsonObject
import com.mints.street.api.BaiduApi
import com.mints.street.api.MainApi
import com.mints.street.bean.*
import com.mints.street.netwrok.baidu.BaiduHttpManager
import com.mints.street.netwrok.common.HttpManager
import com.trello.rxlifecycle2.LifecycleProvider
import io.reactivex.Observable
import retrofit2.Response
import retrofit2.http.Body
object BaiduModel {
/**
* 国外
*/
// fun suggestionPlaceAbroad(lifecycleProvider: LifecycleProvider<Any>?, map: Map<String, Any>): Observable<Response<BaseResponse<Any>>> {
// return BaiduHttpManager.getInstance()
// .execute(lifecycleProvider, BaiduApi.newInstance().suggestionPlaceAbroad(map))
// }
fun suggestionPlaceAbroad(lifecycleProvider: LifecycleProvider<Any>?, map: String,map2 :String,map3: String,map4: String): Observable<Response<BaseResponse<Any>>> {
return BaiduHttpManager.getInstance()
.execute(lifecycleProvider, BaiduApi.newInstance().suggestionPlaceAbroad(map,map2,map3,map4))
}
}
\ No newline at end of file
package com.mints.street.netwrok.baidu;
import com.google.gson.Gson;
import com.mints.street.bean.BaseResponse;
import com.mints.street.manager.UserManager;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* Description:gson全局解析
*/
public class BaiduGsonConverterFactory extends Converter.Factory {
private final Gson gson;
public static BaiduGsonConverterFactory create() {
return create(new Gson());
}
public static BaiduGsonConverterFactory create(Gson gson) {
return new BaiduGsonConverterFactory(gson);
}
private BaiduGsonConverterFactory(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
this.gson = gson;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
return new GsonResponseBodyConverter<>(gson, type);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return new GsonRequestBodyConverter<>(gson, type);
}
// 这里创建从ResponseBody其它类型的Converter
// 主要用于对响应体的处理
final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final Type type;
GsonResponseBodyConverter(Gson gson, Type type) {
this.gson = gson;
this.type = type;
}
@Override
public T convert(ResponseBody value) throws IOException {
Reader reader = value.charStream();
try {
T t = gson.fromJson(reader, type);
// loginInvalid(t);
return t;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ignored) {
ignored.printStackTrace();
}
}
}
/**
* 用户登陆失效
*
* @param t
*/
private void loginInvalid(T t) {
if (t instanceof BaseResponse) {
BaseResponse br = (BaseResponse) t;
int code = br.getstatus();
if (code == 401) {
try {
UserManager.Companion.getINSTANCE().userLogout();
// Activity forwardActivity = ForegroundOrBackground.getApp_activity();
// if (forwardActivity != null) {
// if (!forwardActivity.isFinishing()) {
// forwardActivity.startActivity(new Intent(forwardActivity, WxLoginActivity.class));
// }
// }
} catch (Exception e) {
}
}
}
}
}
// 在这里创建 从自定类型到ResponseBody 的Converter
// 主要用于对Part、PartMap、Body注解的处理
final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private final Charset UTF_8 = StandardCharsets.UTF_8;
private final Gson gson;
private final Type type;
GsonRequestBodyConverter(Gson gson, Type type) {
this.gson = gson;
this.type = type;
}
@Override
public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
gson.toJson(value, type, writer);
writer.flush();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
}
package com.mints.street.netwrok.baidu;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import okhttp3.Interceptor;
/**
* Created by jeme on 2019/1/31
*/
public class BaiduHttpConfiguation {
//超时时间
private int mDefaultTimeOut = 30;
//缓存时间
private int mDefaultCacheTimeOut = 10 * 1024 * 1024;
//服务端根路径
private String mBaseUrl;
//缓存文件名
private String mCacheDirName;
//http head
private Map<String, String> mHeaders;
//拦截器
private List<Interceptor> mInterceptor = new ArrayList<>();
private BaiduHttpConfiguation() {
}
public static BaiduHttpConfiguation create(String baseUrl){
BaiduHttpConfiguation thiz = new BaiduHttpConfiguation();
thiz.setBaseUrl(baseUrl);
return thiz;
}
public BaiduHttpConfiguation setBaseUrl(String baseUrl){
mBaseUrl = baseUrl;
return this;
}
public String getBaseUrl(){
return mBaseUrl;
}
public BaiduHttpConfiguation setCacheDirName(String cacheDirName){
mCacheDirName = cacheDirName;
return this;
}
public String getCacheDirName(){
return mCacheDirName;
}
public BaiduHttpConfiguation setTimeOut(int timeOut){
mDefaultTimeOut = timeOut;
return this;
}
public BaiduHttpConfiguation setCacheDirName(int timeOut){
mDefaultCacheTimeOut = timeOut;
return this;
}
public int getTimeOut(){
return mDefaultTimeOut;
}
public int getCacheTimeOut(){
return mDefaultCacheTimeOut;
}
public BaiduHttpConfiguation setHeads(Map<String,String> heads){
if(mHeaders == null){
mHeaders = heads;
}else {
mHeaders.putAll(heads);
}
return this;
}
public Map<String,String> getHeads(){
return mHeaders;
}
public BaiduHttpConfiguation addInterceptor(Interceptor interceptor){
mInterceptor.add(interceptor);
return this;
}
public List<Interceptor> getInterceptors(){
return mInterceptor;
}
}
package com.mints.street.netwrok.baidu;
import com.fry.base.global.Constants;
import com.mints.street.api.BaiduApi;
import com.mints.street.bean.BaseResponse;
import com.mints.street.netwrok.base.HttpConfiguation;
import com.mints.street.netwrok.base.RetrofitClient;
import com.mints.street.netwrok.common.HttpErrorProcess;
import com.trello.rxlifecycle2.LifecycleProvider;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.utils.RxUtils;
import retrofit2.Response;
/**
* Created by jeme on 2019/1/31
*/
public class BaiduHttpManager {
private BaiduRetrofitClient mDefaultClient;
private BaiduRetrofitClient mTimeClient;
private static class SingletonHolder {
private static BaiduHttpManager INSTANCE = new BaiduHttpManager();
}
public static BaiduHttpManager getInstance() {
return SingletonHolder.INSTANCE;
}
private BaiduHttpManager() {
mDefaultClient = new BaiduRetrofitClient(
BaiduHttpConfiguation.create(BaiduApi.Companion.getBAIDU_IP())
);
}
public BaiduRetrofitClient getDefaultClient() {
return mDefaultClient;
}
public BaiduRetrofitClient getTimeClient() {
if (mTimeClient == null) {
mTimeClient = new BaiduRetrofitClient(
BaiduHttpConfiguation.create(Constants.getBaseUrl())
.setTimeOut(5000));
}
return mTimeClient;
}
public <T> T getDefaultServices(Class<T> clz) {
return getDefaultClient().create(clz);
}
public <B extends BaseResponse, T extends Response<B>>
Observable<T> execute(LifecycleProvider life, final Observable<T> observable) {
Observable<T> newObservable = Observable.just(observable)
.observeOn(Schedulers.io())
.flatMap((Function<Observable<T>, ObservableSource<T>>) tObservable -> {
// ServerTimeHelper.requestServerTime();
return observable;
})
.observeOn(AndroidSchedulers.mainThread());
if (life != null) {
newObservable = newObservable.compose(RxUtils.bindToLifecycle(life));
}
return newObservable
.compose(RxUtils.schedulersTransformer())
.compose(RxUtils.exceptionTransformer())
.compose(HttpErrorProcess.businessExceptionTransformer());
}
}
package com.mints.street.netwrok.baidu;
import android.content.Context;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.fry.base.BuildConfig;
import com.mints.street.netwrok.base.HttpConfiguation;
import com.mints.street.netwrok.common.GsonConverterFactory;
import com.mints.street.netwrok.common.OkHttpInterceptor;
import com.mints.street.utils.encry.AESUtils;
import com.orhanobut.logger.Logger;
import java.util.concurrent.TimeUnit;
import me.goldze.mvvmhabit.http.cookie.CookieJarImpl;
import me.goldze.mvvmhabit.http.cookie.store.PersistentCookieStore;
import me.goldze.mvvmhabit.utils.Utils;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
/**
* Created by mcg
*/
public class BaiduRetrofitClient {
public BaiduHttpConfiguation mHttpConfig;
private Context mContext = Utils.getContext();
private OkHttpClient mOkHttpClient;
private Retrofit mRetrofit;
public BaiduRetrofitClient(@NonNull BaiduHttpConfiguation configuation) {
mHttpConfig = configuation;
if (TextUtils.isEmpty(configuation.getBaseUrl())) {
throw new RuntimeException("baseUrl 不能为空");
}
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
.cookieJar(new CookieJarImpl(new PersistentCookieStore(mContext)))
.connectTimeout(mHttpConfig.getTimeOut(), TimeUnit.SECONDS)
.writeTimeout(mHttpConfig.getTimeOut(), TimeUnit.SECONDS)
.readTimeout(mHttpConfig.getTimeOut(), TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS));
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> {
if (TextUtils.isEmpty(message)) return;
String s = message.substring(0, 1);
String request = message.substring(0, 4);
if ("{".equals(s) || "[".equals(s)) {
Logger.json(message);
} else if (request.contains("-->") || request.contains("<--")) {
Logger.d("Method" + message);
} else {
Logger.d("params:" + message);
}
});
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
clientBuilder.interceptors().add(logging);
}
OkHttpInterceptor okHttpInterceptor = new OkHttpInterceptor(AESUtils.getDefaultKey());
clientBuilder.interceptors().add(okHttpInterceptor);
mOkHttpClient = clientBuilder.build();
mRetrofit = new Retrofit.Builder()
.client(mOkHttpClient)
.addConverterFactory(BaiduGsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(mHttpConfig.getBaseUrl())
.build();
}
/**
* create you ApiService
* Create an implementation of the API endpoints defined by the {@code service} interface.
*/
public <T> T create(final Class<T> service) {
if (service == null) {
throw new RuntimeException("Api service is null!");
}
return mRetrofit.create(service);
}
}
{
"version": 2,
"artifactType": {
"type": "APK",
"kind": "Directory"
},
"applicationId": "com.mints.street",
"variantName": "processStreetpkgDebugResources",
"elements": [
{
"type": "SINGLE",
"filters": [],
"versionCode": 1,
"versionName": "1.0.0",
"outputFile": "streetpkg_1.0.0.apk"
}
]
}
\ No newline at end of file
{
"version": 2,
"artifactType": {
"type": "APK",
"kind": "Directory"
},
"applicationId": "com.mints.street",
"variantName": "processStreetpkgReleaseResources",
"elements": [
{
"type": "SINGLE",
"filters": [],
"versionCode": 1,
"versionName": "1.0.0",
"outputFile": "streetpkg_1.0.0.apk"
}
]
}
\ No newline at end of file
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