2016-12-22 10 views

答えて

0

をどのように行うことができます。

コンパイル 'com.squareup.okhttp3:ログ・インターセプター:3.4.1'
コンパイル 「com.squareup.retrofit2:改造:近道は存在しない2.1.0'

OkHttpClient.Builder builder = new OkHttpClient.Builder(); 
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); 
       httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); 
       builder.networkInterceptors().add(httpLoggingInterceptor); 

OkHttpClient client = new OkHttpClient.Builder() 
         .addInterceptor(httpLoggingInterceptor).build(); 

retrofit = new Retrofit.Builder() 
         .baseUrl(NetworkConstsParkCloud.BASE_URL) 
         .addConverterFactory(GsonConverterFactory.create()) 
         .client(client) 
         .build(); 

、あなたはAndroidがとにかくボンネットの下にOkHttp使用する上で、4.4の時点で、okhttpなしのHttpURLConnectionを改造を使用することはできません。 https://github.com/google/agera/issues/22

-1

を使用して独自のロガーに

  • ログを表示または却下するための組み込みが不要に
  • のProgressBarハンドラAPIを呼び出す私が作られたシンプルなクラス 優位

    1. 共通クラスフォーマット
    2. Multipart inbuilt ie

      HashMap<String, File> fileParams = new HashMap<>(); if (selectedImage != null) fileParams.put("image", new File(selectedImage)); Retrofit.getInstance("user/editprofile", params, fileParams)

    レトロフィット共通クラス

    /* 
    * Created by RajeshKushvaha on 19-10-16 
    */ 
    
    public abstract class Retrofit implements Callback<ResponseBody> { 
    private static final String BASE_URL = "http://192.168.1.100/apps/demo/web/v1/"; //Local 
    
    private ProgressDialog progress; 
    
    public Retrofit() { 
    } 
    
    public Retrofit(Context context) { 
        if (progress != null && progress.isShowing()) { 
         progress.dismiss(); 
        } 
        progress = new ProgressDialog(context, R.style.ProgressDialog); 
        progress.setIndeterminate(true); 
        progress.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.shape_drawable_progress)); 
        progress.setCancelable(false); 
        progress.setCanceledOnTouchOutside(false); 
        progress.show(); 
    } 
    
    public Retrofit(Context context, boolean isLoadMore) { 
        if (isLoadMore) return; 
        if (progress != null && progress.isShowing()) { 
         progress.dismiss(); 
        } 
        progress = new ProgressDialog(context, R.style.ProgressDialog); 
        progress.setIndeterminate(true); 
        progress.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.shape_drawable_progress)); 
        progress.setCancelable(false); 
        progress.setCanceledOnTouchOutside(false); 
        progress.show(); 
    } 
    
    public static Call<ResponseBody> getInstance(String endPoint, 
                  HashMap<String, String> params) { 
        return getInstance(endPoint, params, null); 
    } 
    
    public static Call<ResponseBody> getInstance(String endPoint, 
                  HashMap<String, String> params, 
                  HashMap<String, File> files) { 
        HashMap<String, RequestBody> bodyParams = null; 
    
        Logger.e("URL", BASE_URL + endPoint); 
        if (files != null && files.size() > 0) { 
         bodyParams = new HashMap<>(); 
         for (Map.Entry<String, String> entry : params.entrySet()) { 
          Logger.e("params", entry.getKey() + "\t" + entry.getValue()); 
          bodyParams.put(entry.getKey(), createPartFromString(entry.getValue())); 
         } 
         for (Map.Entry<String, File> entry : files.entrySet()) { 
          Logger.e("params", entry.getKey() + "\t" + entry.getValue().getPath()); 
          String fileName = entry.getKey() + "\"; filename=\"" + entry.getValue().getName(); 
          bodyParams.put(fileName, createPartFromFile(entry.getValue())); 
         } 
        } else { 
         for (Map.Entry<String, String> entry : params.entrySet()) { 
          Logger.e("params", entry.getKey() + "\t" + entry.getValue()); 
         } 
        } 
    
        //Added for handle timout you can skip this 
        OkHttpClient client = new OkHttpClient.Builder() 
          .connectTimeout(60, TimeUnit.SECONDS) 
          .readTimeout(60, TimeUnit.SECONDS) 
          .writeTimeout(60, TimeUnit.SECONDS) 
          .build(); 
    
        ApiInterface apiInterface = new retrofit2.Retrofit.Builder() 
          .baseUrl(BASE_URL) 
          .client(client) 
          .addConverterFactory(GsonConverterFactory.create()) 
          .build().create(Retrofit.ApiInterface.class); 
    
        return bodyParams != null ? apiInterface.methodMultipart(endPoint, bodyParams) : apiInterface.method(endPoint, params); 
    } 
    
    @Override 
    public void onResponse(Call call, Response response) { 
        if (progress != null && progress.isShowing()) progress.dismiss(); 
        String body = null; 
        try {//Converting string to JSONObject 
         if (response.body() != null) { 
          body = ((ResponseBody) response.body()).string(); 
          JSONObject object = new JSONObject(body); 
          Logger.e("Response", call.request().url().toString() + "\n" + object.toString()); 
          onResponse(response.code(), object); 
         } else { 
          body = response.errorBody().string(); 
          JSONObject object = new JSONObject(body); 
          Logger.e("Response", call.request().url().toString() + "\n" + object.toString()); 
          onFailed(response.code(), object.optString("message")); 
         } 
        } catch (JSONException | IOException e) { 
         e.printStackTrace(); 
         if (body != null) Logger.e(body); 
         onFailed(response.code(), "Something went wrong!\n Please try again"); 
        } 
    } 
    
    @Override 
    public void onFailure(Call call, Throwable t) { 
        Logger.e("Response", call.request().url().toString() + "\n" + t.toString()); 
        if (progress != null && progress.isShowing()) progress.dismiss(); 
        if (t instanceof ConnectException || t instanceof SocketTimeoutException || t instanceof UnknownHostException) { 
         onFailed(0, "Failed to connect with server!"); 
        } else if (t instanceof IOException) { 
         onFailed(0, "No internet connection!"); 
        } else if (t instanceof RequestException) { 
         onFailed(0, "Request timeout!"); 
        } else { 
         onFailed(0, t.getMessage()); 
        } 
    } 
    
    public interface ApiInterface { 
    
        @FormUrlEncoded 
        @POST 
        Call<ResponseBody> method(@Url String endpoint, 
               @FieldMap HashMap<String, String> fields); 
    
        @Multipart 
        @POST 
        Call<ResponseBody> methodMultipart(@Url String endpoint, 
                 @PartMap HashMap<String, RequestBody> fields); 
    } 
    
    private static RequestBody createPartFromString(String value) { 
        return RequestBody.create(MediaType.parse("multipart/form-data"), value); 
    } 
    
    private static RequestBody createPartFromFile(File file) { 
        return RequestBody.create(MediaType.parse("multipart/form-data"), file); 
    } 
    
    public abstract void onResponse(int statusCode, JSONObject jResponse); 
    
    public abstract void onFailed(int statusCode, String message); 
    } 
    

    (Postメソッドのために)使用方法
    HashMap<String, String> params = new HashMap<>(); 
         params.put("email", email); 
         params.put("password", password); 
    
         Retrofit.getInstance("user/login", params)//user/login was endpoint 
           .enqueue(new Retrofit(ForgetPasswordActivity.this/*pass context if you want progressbar*/) { 
            @Override 
            public void onResponse(int statusCode, JSONObject jResponse) { 
             //handle your response 
            } 
    
            @Override 
            public void onFailed(int statusCode, String message) { 
             showToast(message); 
            } 
           }); 
    
    +0

    ログで記録する:D – Amit

    +0

    なぜdownwote?、あなたを取得しないでください:( –

    関連する問題