更多...http://blog.csdn.net/zl18603543572?viewmode=listjava
很累,累到想要放棄,可是放棄以後將會是一無全部,又不能放棄,android
惟有堅持,惟有給自憶打氣,才能更勇敢的走下去,由於無路可退,只能前行,json
時光一去不復返,每一天都不可追回,因此要更珍惜每一存光陰api
不閱世界百態,怎懂滄桑世故四字,數組
不觀千嬌百媚花開,豈知繁華與浮華,服務器
惟有經歷,才能明瞭cookie
public class RetrofitRxJavaHttpUtils { public static final String BASE_URL = "http://192.168.1.103:8080/"; private RetrofitRxJavaHttpUtils() { /** * 在調用構造的時候分別對OkhttpClient 與Retrofit進行初時化操做 */ client = getHttpClientInstance(); retrofit = getRetrofitInstance(); } /** * 獲取網絡請求工具類單例對象 */ private static RetrofitRxJavaHttpUtils utils; public static RetrofitRxJavaHttpUtils getInstance() { if (utils == null) { synchronized (RetrofitRxJavaHttpUtils.class) { utils = new RetrofitRxJavaHttpUtils(); } } return utils; } }
在獲取okhttpClient實例對象的時候,設置了一些通用的信息,例如請求頭信息,請求參數信息,以及網絡超時,Cookie等等因此下面的這一段代碼量比較大網絡
/** * 獲取oKhttpClient 的實例 * 在初始化的時候設置一些統一性的操做 */ private static OkHttpClient client; private OkHttpClient getHttpClientInstance() { if (client == null) { synchronized (RetrofitRxJavaHttpUtils.class) { OkHttpClient.Builder builder = new OkHttpClient.Builder(); /** * 設置添加公共的請求參數 */ Interceptor addQueryParameterInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Request request; String method = originalRequest.method(); Headers headers = originalRequest.headers(); HttpUrl modifiedUrl = originalRequest.url().newBuilder() // Provide your custom parameter here .addQueryParameter("commonKey", "android") .addQueryParameter("version", "1.0.0") .build(); request = originalRequest.newBuilder().url(modifiedUrl).build(); return chain.proceed(request); } }; builder.addInterceptor(addQueryParameterInterceptor); /** * 添加請求頭 */ Interceptor headerInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Request.Builder requestBuilder = originalRequest.newBuilder() .header("AppType", "TPOS") .header("Content-Type", "application/json") .header("Accept", "application/json") .method(originalRequest.method(), originalRequest.body()); Request request = requestBuilder.build(); return chain.proceed(request); } }; builder.addInterceptor(headerInterceptor); /** * 服務端可能須要保持請求是同一個cookie,主要看各自需求 * compile 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0' */ CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); builder.cookieJar(new JavaNetCookieJar(cookieManager)); /** * 設置請求超時時間 */ builder.connectTimeout(15, TimeUnit.SECONDS); builder.readTimeout(20, TimeUnit.SECONDS); builder.writeTimeout(20, TimeUnit.SECONDS); /** * 設置請求加載錯誤不從新鏈接 */ builder.retryOnConnectionFailure(false); client = builder.build(); } } return client; }
/** * 獲取Retrofit實例 * 這裏面使用到了OkhttpClient ,在這以前先要將client對象進行初始化操做 */ private static Retrofit retrofit; private Retrofit getRetrofitInstance(){ if (retrofit==null){ synchronized (RetrofitRxJavaHttpUtils.class){ if(retrofit==null){ retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) //設置 Json 轉換器 .addConverterFactory(GsonConverterFactory.create()) //RxJava 適配器 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(client) .build(); } } } return retrofit; }
在發起請求的時候 ,先經過retrofit對象create服務對象,而後再調起異步請求併發
定義服務請求接口app
public interface RetrofitRxInterface { /** * 提交KEY VALEU 形式的參數到服務器 * @param retrofit * @param str * @return */ @POST("/OkhttpAppLication//test") Observable<HttpResult> request(@Query("username") String retrofit, @Query("password") String str); /** * 提交一個Json數據到服務器 * @param apiInfo * @return */ @POST("/OkhttpAppLication//test") Call<ResponseBody> username(@Body UserInfo apiInfo); /** * 提交一個數組信息到服務器 * @param id * @param linked * @return */ @GET("/OkhttpAppLication//test") Call<ResponseBody> submitArray(@Query("id") String id, @Query("linked[]") String... linked); /** * 上傳單個文件 * @param description * @param imgs * @return */ @Multipart @POST("/OkhttpAppLication/LoadFileServlet") Call<ResponseBody> uploadFile(@Part("fileName") String description, @Part("file")RequestBody imgs); /** * 上傳多個文件 * @param pictureName * @param params * @return */ @Multipart @POST("/OkhttpAppLication/LoadFileServlet") Call<ResponseBody> uploadFiles(@Part("pictureName") RequestBody pictureName, @PartMap Map<String, RequestBody> params); }
而後再在發起請求的時候經過retrofit來使用
/** * 提交參數爲KEY - VALUE 形式 * @param name * @param password */ public void asyncPostKeyValueRequest(String name, String password) { RetrofitRxInterface user = retrofit.create(RetrofitRxInterface.class); Observable<HttpResult> observable = user.request(name, password); observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<HttpResult>() { @Override public void onCompleted() { /** * 請求執行完畢執行此方法 */ System.out.println("complete "); } @Override public void onError(Throwable e) { System.out.println("error: " + e.getMessage()); } @Override public void onNext(HttpResult user) { /** * 獲取服務器數據 */ System.out.println("" + user.toString()); } }); }
在頁面中的使用方法;
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String username = "admin"; String password = "12345"; RetrofitRxJavaHttpUtils.getInstance().asyncPostKeyValueRequest(username,password); } }
備註:
1.使用到了一個RetrofitRxInterface,這是爲Retrofit網絡請求框架進行服務的接口,
2.使用到了一個HttpResult,這個類是用來接收服務器返回數據的與服務器端保持一至就能夠,
/** * 提交JSON數據到服務器 */ public void asyncPostJsonRequest(){ /** * 獲取服務接口 */ RetrofitRxInterface user1 = retrofit.create(RetrofitRxInterface.class); /** * 構造提交數據 */ UserInfo userInfo = new UserInfo(); userInfo.username = "xhao longs"; userInfo.password = "admin"; /** * 發起回調請求 */ Call<ResponseBody> username = user1.username(userInfo); username.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { /** * 請求成功相關回調 */ ResponseBody body = response.body(); try { String string = body.string(); System.out.println(string); } catch (IOException e) { e.printStackTrace(); } String s = body.toString(); System.out.println("body string "+s); } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { } }); }
調用方法:
public class MainActivity extends AppCompatActivity { public static final String BASE_URL = "http://192.168.1.103:8080/OkhttpAppLication/test"; @Bind(R.id.click_me_BN) Button clickMeBN; @Bind(R.id.result_TV) TextView resultTV; private SubscriberOnNextListener getTopMovieOnNext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RetrofitRxJavaHttpUtils.getInstance().asyncPostJsonRequest(); }}
提交的數據格式 爲:
{"password":"admin","username":"xhao longs"}
6.上傳單個文件(這裏上傳的是圖片)
public void asyncUpLoadFile(){ String filename = "/storage/emulated/0/custom/2016/6/18//20160623135328.PNJE"; /** * 封裝上傳文件 */ File picture= new File(filename); RequestBody requestFile = RequestBody.create(MediaType.parse("application/octet-stream"), picture); /** * 調起上傳單文件服務請求接口併發起回調請求 */ RetrofitRxInterface user = retrofit.create(RetrofitRxInterface.class); /** * 這裏上傳的文件名稱爲dsf */ Call<ResponseBody> responseBodyCall = user.uploadFile("dsf", requestFile); responseBodyCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { ResponseBody body = response.body(); try { String string = body.string(); System.out.println(string); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { System.out.println("err:_ "+t.getMessage()); } }); }
調用方法
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RetrofitRxJavaHttpUtils.getInstance().asyncUpLoadFile(); }}
7.上傳多個文件:
public void asyncUpLoadFiles(){ String filename = "/storage/emulated/0/custom/2016/6/18//20160623135328.PNJE"; RequestBody pictureNameBody = RequestBody.create(MediaType.parse("Content-Disposition"), "form-data;name=pictureName"); /** * 封裝文件 */ File picture= new File(filename); /** * 獲取請求RequestBody */ RequestBody requestFile = RequestBody.create(MediaType.parse("application/octet-stream"), picture); /** * 封裝上傳文件信息 * 這裏只封裝了一張圖片 */ Map<String, RequestBody> params = new HashMap<>(); params.put("picture\"; filename=\"" + picture.getName() + "", requestFile); /** * 調起服務請求接口併發起回調請求 */ RetrofitRxInterface user = retrofit.create(RetrofitRxInterface.class); Call<ResponseBody> responseBodyCall = user.uploadFiles(pictureNameBody, params); responseBodyCall.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) { ResponseBody body = response.body(); try { String string = body.string(); System.out.println(string); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { System.out.println("err:_ "+t.getMessage()); } }); }
調用方法與上傳單文件方法一至