Retrofit(リビルド-簡単アクセス)


前の記事では、retrofitに関するいくつかの使い方を紹介しましたが、まだ具体的ではありません.次の記事では、萌えアプリのネットワークリクエストを再構築することに重点を置きます.
この記事では、ログインインタフェースの再構築について説明します.次に、アパッチを使用したhttpclientメソッドを貼ります(現在、グーグルでは使用を推奨していません)
public static String execute(String url, String jsonStr, String filePath,
            int conTimeout, int soTimeout) {
        //     post        ,        ,   null,
        //           ,              
        //   filePath   ,      
        // conTimeout     ,     ,   0        
        // soTimeout TCP  ,     ,   0   ,     
        File f1 = new File(Constants.FILECACHE_DIR);
        if (!f1.exists()) {
            f1.mkdirs();
        }

        try {
            HttpParams httpParams = null; // http  
            HttpClient httpClient = null; // http    
            HttpResponse response = null; // http    
            String reJsonStr = null; //       json   
            HttpPost httpPost = null;

            MultipartEntity entity = null; // post   
            int sTimeout = 0; // socket timeout
            int cTimeout = 0; // connection timeout
            if (conTimeout <= 0) {
                cTimeout = Constants.ConnectionTimeout;
            } else {
                cTimeout = conTimeout;
            }
            if (soTimeout <= 0) {
                sTimeout = Constants.SocketTimeout;
            } else {
                sTimeout = soTimeout;
            }
            //   http    
            httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, cTimeout);//     
            HttpConnectionParams.setSoTimeout(httpParams, sTimeout);//     
            HttpConnectionParams.setSocketBufferSize(httpParams,
                    Constants.SocketBufferSize);

            httpClient = new DefaultHttpClient(httpParams);
            entity = new MultipartEntity();
            //   
            String pp = Base64.encodeToString(jsonStr.getBytes(),
                    Base64.DEFAULT);
            StringBody pParmas = null;
            Log.e("jiang",jsonStr+"~~~~~~~"+pp);
            try {
                pParmas = new StringBody(pp);

            } catch (UnsupportedEncodingException e) {
                if (Constants.TEST)
                    e.printStackTrace();
            }
            entity.addPart(Constants.SENDATAP, pParmas); //     p

            if (filePath != null) {
                //     f
                FileBody fileBody = new FileBody(new File(filePath));
                entity.addPart(Constants.SENDATAF, fileBody); //     f
            }


            httpPost = new HttpPost(url);
            httpPost.setEntity(entity);

            try {
                response = httpClient.execute(httpPost);
                int code = response.getStatusLine().getStatusCode();

                if (code == HttpStatus.SC_OK) {
                    HttpEntity en = response.getEntity();
                    String respon = EntityUtils.toString(en);

                    reJsonStr = new String(
                            Base64.decode(respon, Base64.DEFAULT));
                    Log.e("jiang",respon+"~~~~~~~~~~~~"+reJsonStr);
                }
                JSONObject obj_data = new JSONObject(reJsonStr);
                String c = obj_data.getString("c");

                if (c.equals("1")) {

                }

                return reJsonStr;

            } catch (ConnectTimeoutException e) {

                  //            TODO              

                httpClient.getConnectionManager().closeExpiredConnections();

                return null;
            }
        } catch (Exception e) {

            return null;
        } finally {

        }
    }

大体のロジックはマルチブロックpostで伝達して、第1部分のパラメータ“p”、第2部分のパラメータ“f”、第1部分はjsonのデータ型にカプセル化して、stringに転換してbase 64の符号化を行って、第2部分はファイルの送信を担当して、この編は言いません.次にretrofitを貼って使用します
retrofit
 UpXlUser upXlUser = new UpXlUser();
        upXlUser.setU("xxxx");
        upXlUser.setP("xxxx");
        Gson gson = new Gson();
        String str = gson.toJson(upXlUser);
        String baseStr = Base64.encodeToString(str.getBytes(),
                Base64.DEFAULT);
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), baseStr);
        Subscription subscription = clientApi.getXlLogin(requestBody)
                .compose(SchedulersCompat.<Response>applyIoSchedulers())
                .subscribe(new Subscriber<Response>() {
                    @Override
                    public void onCompleted() {  
                        hideLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) { 
                        showToast("    ");
                        hideLoadingDialog();
                    }

                    @Override
                    public void onNext(Response transDao) {


                    }
                });

基本情報アカウントとパスワードはjavabeanにカプセル化され、gsonを利用してjsonに変換されてbase 64符号化され、text/plainとしてアップロードされることに注意してください.
apiインタフェース
    @Multipart @POST("/xl/v2_user_login") Observable<Response> getXlLogin(@Part("p") RequestBody upTrans);

Multipartを知らない人はこの文章を読むことができます.@MUltipartでの注釈であれば,内部で必ずPart注釈,ブロックリクエストを用い,複数あればPartMapを利用する.
サービス初期化
 @Provides
    @Singleton
    public OkHttpClient provideOkHttpClient(HttpLoggingInterceptor httpLoggingInterceptor,HttpInterceptor httpInterceptor,ProgressInterceptor progressInterceptor) {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);
        client.setWriteTimeout(10, TimeUnit.SECONDS);
        client.setReadTimeout(30, TimeUnit.SECONDS);
        client.interceptors().add(httpLoggingInterceptor);
        client.interceptors().add(httpInterceptor);
        return client;
    }

httpのlog印刷を加え、同時にブロックを書き換え、戻り体をブロックするためにbase 64トランスコードを行うことを目的としている.
        Request orginRequest = chain.request();
        Request requst = orginRequest.newBuilder()
                .build();
        Response response = chain.proceed(requst);
        //     
        Response pp = getBase64Response(response);
        if (pp != null) return pp;
        return response;
 private Response getBase64Response(Response response) throws IOException {
        if (response.body() != null) {

            String bodyString = response.body().string();
            /*  */
            String pp = new String(
                    Base64.decode(bodyString, Base64.DEFAULT));
            return response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), pp))
                    .build();
        }
        return null;
    }

OK、基本的なネットアクセスはこれで終わります.簡単で難点はありません.次の文章では、画像をダウンロードする方法を紹介します.