添加依赖:
compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3'
添加网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
同步调用Demo
//创建Retrofit对象 Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://115.215.206.23:8880") .build(); //创建调用API请求 LogApi logApi = retrofit.create(LogApi.class); Call<ResponseBody> call = logApi.getCode("log","18799155201","123456"); try { Response<ResponseBody> bodyResponse = call.execute(); String body = bodyResponse.body().string();//获取返回体的字符串 Log.i("snow",body); } catch (IOException e) { e.printStackTrace(); }
接口申明如下:
public interface LogApi { @GET("/getLogCode.action?") Call<LogInfo> getCode(@Query("reqType") String reqType,@Query("userId") String userId,@Query("passWord") String passWord); }
注意:会提示NetworkOnMainThreadException,原因你懂的。
异步调用Demo
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://114.215.204.23:8880") .addConverterFactory(GsonConverterFactory.create()) .build(); LogApi logApi = retrofit.create(LogApi.class); Call<LogInfo> call = logApi.getCode("log","18799155201","123456"); call.enqueue(new Callback<LogInfo>() { @Override public void onResponse(Call<LogInfo> call, Response<LogInfo> response) { Log.i("snow", "response=" + response.body().getMsg()); } @Override public void onFailure(Call<LogInfo> call, Throwable t) { Log.i("snow", "onFailure=" + t.getMessage()); } });
注解 | 描述 |
---|---|
@Path | variable substitution for the API endpoint (i.e. username will be swapped for {username} in the URL endpoint). |
@Query | specifies the query key name with the value corresponding to the value of that annotated parameter. |
@Body | payload for the POST call |