@Path:所有在网址中的参数(URL的问号前面),如:
就可以添加认证。
http://102.10.10.132/api/Accounts/{accountId}
http://102.10.10.132/api/Comments?access_token={access_token}
@QueryMap:相当于多个@Query
@GET("index.php/app/device/init") Observable<InitBean> getAuthCode(@QueryMap Map<String, Object> param);
@Field:用于POST请求,提交单个数据 ,使用@Field时记得添加@FormUrlEncoded
@FormUrlEncoded @POST("index.php/app/pay/index") Observable<WechatPay> payWechat(@Field("money") String money, @Field("guid") String guid, @Field("store_id") String store_id, @Field("shop_id") String shop_id, @Field("auth_code") String auth_code);
@Body:相当于多个@Field,以对象的形式提交
同时访问网络时需要DIGEST认证,认证方式如下:
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.MalformedChallengeException;
import org.apache.http.impl.auth.DigestScheme;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpRequest;
import java.io.IOException;
import okhttp3.Authenticator;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
public class DigestAuthenticator implements Authenticator {
DigestScheme mDigestScheme = new DigestScheme();
org.apache.http.auth.Credentials mCredentials = null;
public DigestAuthenticator(String username,String password) {
mCredentials = new org.apache.http.auth.UsernamePasswordCredentials(username, password);
}
@Override
public Request authenticate(Route route, Response response) throws IOException {
try {
mDigestScheme.processChallenge(new BasicHeader("WWW-Authenticate", response.header("WWW-Authenticate")));
} catch (MalformedChallengeException e) {
}
org.apache.http.HttpRequest request = new BasicHttpRequest(
response.request().method(),
response.request().url().toString()
);
String authHeader;
try {
authHeader = mDigestScheme.authenticate(mCredentials, request).getValue();
} catch (AuthenticationException e) {
authHeader = null;
}
if (authHeader == null) {
return null;
}
return response.request().newBuilder().addHeader("Authorization", authHeader).build();
}
}
mOkHttpClient = new OkHttpClient.Builder()
.cache(cache)
.addInterceptor(mRewriteCacheControlInterceptor)
.addNetworkInterceptor(mRewriteCacheControlInterceptor)
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.authenticator(new DigestAuthenticator(username,password))
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Base_URL)
.client(mOkHttpClient)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
就可以添加认证。