當前位置:首頁 » 密碼管理 » retrofit請求加密

retrofit請求加密

發布時間: 2022-08-07 07:28:40

⑴ 如何使用retrofit發送網路請求

用Retrofit發送網路請求和解析json的實例
Retrofit是Android的一個非常好用的開源HTTP Request。現在介紹一下Retrofit是如何使用的。。。。
首先是導入Retrofit包,
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.squareup.retrofit:retrofit:1.9.0'
}1234512345

然後是根據API的JSON數據建立一個數據類
URL:http://apistore..com/microservice/weather?citypinyin=beijing
{
errNum: 0,
errMsg: "success",
retData: {
city: "北京", //城市
pinyin: "beijing", //城市拼音
citycode: "101010100", //城市編碼
date: "15-02-11", //日期
time: "11:00", //發布時間
postCode: "100000", //郵編
longitude: 116.391, //經度
latitude: 39.904, //維度
altitude: "33", //海拔
weather: "晴", //天氣情況
temp: "10", //氣溫
l_tmp: "-4", //最低氣溫
h_tmp: "10", //最高氣溫
WD: "無持續風向", //風向
WS: "微風(<10m/h)", //風力
sunrise: "07:12", //日出時間
sunset: "17:44" //日落時間
}
}
21222324

以下是數據類:
public class Result {
private String errNum;
private String errMsg;
private WeatherData retData;

public void setErrNum(String errNum) {
this.errNum = errNum;
}

public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}

public WeatherData getRetData() {
return retData;
}

public void setRetData(WeatherData retData) {
this.retData = retData;
}

public String getErrNum() {
return errNum;
}

public String getErrMsg() {
return errMsg;
}

}

public class WeatherData {

private String city; //城市
private String pinyin;//城市拼音
private String citycode; //城市編碼
private String date; //日期
private String time;//發布時間
private String postCode; //郵編
private String longitude;//經度
private String latitude; //維度
private String altitude;//海拔
private String weather; //天氣情況
private String temp; //氣溫
private String l_tmp; //最低氣溫
private String h_tmp; //最高氣溫
private String WD; //風向
private String WS; //風力
private String sunrise;//日出時間
private String sunset;//日落時間

//setter和getter就不貼了

}


新建一個MyService的介面,由於之後要在主線程使用(安卓3.0以上主線程不能同步訪問網路),所以這里採用非同步獲取的方式。故增加了Callback< Result > cb
import retrofit.Callback;
import retrofit.http.GET;
import retrofit.http.Query;

public interface MyService {
// URI:http://apistore..com/microservice/weather?citypinyin=beijing

@GET("/microservice/weather")
void getResult(@Query("citypinyin") String citypinyin, Callback<Result> cb);

}12345678910111234567891011

使用RestAdapter來實例化MyService;
import retrofit.RestAdapter;

public class MyRestClient {

private static String API_URL = "http://apistore..com";

public static MyService getService() {
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)//設置站點路徑
.setLogLevel(RestAdapter.LogLevel.FULL)//設置log的級別
.build();

MyService myService = restAdapter.create(MyService.class);

return myService;
}

}

系統調用如下
@Override
public void onStart()
{
super.onStart();
MyRestClient.getService().getResult("beijing",new Callback<Result>() {
@Override
public void success(Result result, Response response) {
Log.i("",result.getRetData().getDate());
}

@Override
public void failure(RetrofitError error) {

}
});

}

別忘了添加網路訪問許可權喲。
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

⑵ 如何使用Retrofit請求非Restful API

1. 首先定義帶泛型的返回結果,Retrofit API 的原生結果映射為這種形式: class Result { String ResultMessage; int ResultCode; T Data; } 2. 處理錯誤的方法和 @朱詩雄 前輩方法差不多,放到作為靜態方法放到 RetroUtil 里,這里 ApiExceptio...

⑶ rxjava+retrofit 怎麼封裝請求參數

定義帶泛型的返回結果,Retrofit API 的原生結果映射為這種形式: class Result { String ResultMessage; int ResultCode; T Data; }

⑷ 如何在Retrofit請求里添加Cookie

你可以自定義一個RequestIntercaptor:
String cookieKey = ...
String cookieValue = ...

RestAdapter adapter = new RestAdapter.Builder()
.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
// assuming `cookieKey` and `cookieValue` are not null
request.addHeader("Cookie", cookieKey + "=" + cookieValue);
}
})
.setServer("http://...")
.build();

YourService service = adapter.create(YourService.class);
從伺服器讀取cookies再交給cookie manager管理:
OkHttpClient client = new OkHttpClient();
CustomCookieManager manager = new CustomCookieManager();
client.setCookieHandler(manager);

RestAdapter adapter = new RestAdapter.Builder()
.setClient(new OkClient(client))
...
.build();
CustomeCookieManager如下:
public class CustomCookieManager extends CookieManager {

// The cookie key we're interested in.
private final String SESSION_KEY = "session-key";

/**
* Creates a new instance of this cookie manager accepting all cookies.
*/
public CustomCookieManager() {
super.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
}

@Override
public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {

super.put(uri, responseHeaders);

if (responseHeaders == null || responseHeaders.get(Constants.SET_COOKIE_KEY) == null) {
// No cookies in this response, simply return from this method.
return;
}

// Yes, we've found cookies, inspect them for the key we're looking for.
for (String possibleSessionCookieValues : responseHeaders.get(Constants.SET_COOKIE_KEY)) {

if (possibleSessionCookieValues != null) {

for (String possibleSessionCookie : possibleSessionCookieValues.split(";")) {

if (possibleSessionCookie.startsWith(SESSION_KEY) && possibleSessionCookie.contains("=")) {

// We can safely get the index 1 of the array: we know it contains
// a '=' meaning it has at least 2 values after splitting.
String session = possibleSessionCookie.split("=")[1];

// store `session` somewhere

return;
}
}
}
}
}
}

⑸ 簡單說下Retrofit怎麼設置請求頭信息

有三種方式:
1、直接在參數里寫 每次訪問的時候都要傳入一下

@GET("weatherservice/citylist")
Observable<WeatherRestBean> queryWeather(@Header("apikey") String apikey,@Query("cityname") String cityname);

2、寫到註解里這樣就少了個參數,但是每定義個介面都要寫一次也是比較麻煩
·
@Headers("apikey:")
@GET("weatherservice/cityid")
Observable<WeatherEntity> query(@Query("cityid")String cityid);

3、在創建Retrofit的時候添加,最方便的方式
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request.Builder builder1 = request.newBuilder();
Request build = builder1.addHeader("apikey", "ac7c302dc489a69082cbee6********").build();
return chain.proceed(build);
}
}).retryOnConnectionFailure(true)
.build();
mRetrofit = new Retrofit.Builder()
.client(client)
.baseUrl(ConstantApi.url)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())

熱點內容
cad解壓錯誤 發布:2024-03-29 15:01:45 瀏覽:78
存儲指令集 發布:2024-03-29 14:39:27 瀏覽:649
資料庫表刪除數據 發布:2024-03-29 14:39:26 瀏覽:367
出c語言整除 發布:2024-03-29 14:28:22 瀏覽:572
芬尼壓縮機 發布:2024-03-29 14:24:11 瀏覽:464
電腦數據實時上傳本地伺服器軟體 發布:2024-03-29 14:07:57 瀏覽:920
尋秦記源碼 發布:2024-03-29 13:56:17 瀏覽:496
linux的備份命令 發布:2024-03-29 13:41:22 瀏覽:383
csgo建議什麼配置 發布:2024-03-29 13:31:44 瀏覽:980
電腦ftp服務如何禁用 發布:2024-03-29 13:24:48 瀏覽:332