应用拦截器

//
//
//
/
/
//xml布局

Button
android:id="@+id/okhttp_json"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“获取Json数据”/>

Button
    android:id="@+id/okhttp_table"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="表单提交"/>


<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <!--ScrollView只能包裹一个直接的子view,否则会报错,解决办法就是放一个容器,然后容器里面有多少控件就没有关系了-->
    <TextView
        android:id="@+id/text_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"/>
</ScrollView>

/
/
/
/
/
/
/
/MainActivity
String url = “http://gank.io/api/data/福利/10/1”;
String url1 =“http://www.zhaoapi.cn/product/getCarts”;
private TextView text_tv;
private Button okhttp_json;
private Button okhttp_table;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_main );
    initView();
}

private void initView() {
    text_tv = (TextView) findViewById( R.id.text_tv );
    okhttp_json = (Button) findViewById( R.id.okhttp_json );
    okhttp_json.setOnClickListener( this );
    okhttp_table = (Button) findViewById( R.id.okhttp_table );
    okhttp_table.setOnClickListener( this );
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.okhttp_json:
            OkhttpUtils.getInstance().doGet( url, new OkhttpUtils.okhttputil() {
                @Override
                public void success(String json) {
                text_tv.setText( json );

                }
            } );
            break;
        case R.id.okhttp_table:
            HashMap<String, String> map = new HashMap<>();
            map.put( "uid","71" );

            OkhttpUtils.getInstance().doPost( url1, map, new OkhttpUtils.okhttputil() {
                @Override
                public void success(String json) {
                 text_tv.setText( json );
                }
            } );
            break;
    }
}

//
//
/
/
/
okhttp封装

private final Handler mHandler;
private final OkHttpClient mOkHttpClient;
private static OkhttpUtils sOkhttpUtils;

private OkhttpUtils(){

    HashMap<String,String> map = new HashMap<>();
    map.put( "source","android" );
    publicParamInterceptor publicParamInterceptor = new publicParamInterceptor( map );

    mHandler = new Handler();
    mOkHttpClient = new OkHttpClient.Builder()
    .writeTimeout( 10,TimeUnit.SECONDS )
    .readTimeout( 10,TimeUnit.SECONDS )
    .connectTimeout( 10,TimeUnit.SECONDS )
    .addInterceptor( publicParamInterceptor )
    .build();

}
public static OkhttpUtils getInstance(){
    if(sOkhttpUtils==null){
        synchronized (OkhttpUtils.class){
            if(sOkhttpUtils==null){
              return   sOkhttpUtils = new OkhttpUtils();
            }
        }
    }
    return sOkhttpUtils;
}
public interface okhttputil{
    void success(String json);
}
public void doGet(String url, final okhttputil ycfokhttputil){
    Request request = new Request.Builder()
            .get()
            .url( url )
            .build();
    Call call = mOkHttpClient.newCall( request );
    call.enqueue( new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            final String json = response.body().string();
            if(response!=null&&response.isSuccessful()){
              if(ycfokhttputil!=null){
                  mHandler.post( new Runnable() {
                      @Override
                      public void run() {
                          ycfokhttputil.success(json);
                      }
                  } );

              }
          }
        }
    } );
}
public void doPost(String url , Map<String,String>map, final okhttputil ycfokhttputil){
    FormBody.Builder builder = new FormBody.Builder();
    if(map!=null){
        for (String key : map.keySet()){
             builder.add( key,map.get( key ) );
        }
    }
    FormBody formBody = builder.build();
    Request request = new Request.Builder()
            .post(formBody)
            .url( url )
            .build();
    Call call = mOkHttpClient.newCall( request );
    call.enqueue( new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            final String json = response.body().string();
            if(response!=null&&response.isSuccessful()){
                if(ycfokhttputil!=null){
                    mHandler.post( new Runnable() {
                        @Override
                        public void run() {
                            ycfokhttputil.success(json);
                        }
                    } );

                }
            }
        }
    } );
}

//
/
/
/
/
/
/

//新建个类实现 implements Interceptor
private final HashMap<String, String> map;

public publicParamInterceptor(HashMap<String, String> map) {
    this.map=map;
}

@Override
public Response intercept(Chain chain) throws IOException {
    Request yuanlairequest = chain.request();
    String url = yuanlairequest.url().toString();
    if(yuanlairequest.method().equalsIgnoreCase( "GET" )){
        if(map!=null&&map.size()>0){
            StringBuilder stringBuilder = new StringBuilder( url );
            for(Map.Entry<String,String>entry:map.entrySet()){
                stringBuilder.append( "&"+entry.getKey()+"="+entry.getValue() );
            }
            url = stringBuilder.toString();
            if(!url.contains( "?" )){
                url=url.replaceFirst( "&" ,"?");
            }
            Log.e( "sss",url+"" );
            Request request = yuanlairequest.newBuilder()
                    .url( url )
                    .build();
        return  chain.proceed( request );
        }
    }else{
         if(map != null && map.size()>0){
             RequestBody body = yuanlairequest.body();
             if(body!=null && body instanceof FormBody){
              FormBody formBody = (FormBody) body;
                 FormBody.Builder builder = new FormBody.Builder();
                 HashMap<String,String> temMap = new HashMap<>();
                 for(int x = 0 ; x<formBody.size();x++){
                    builder.add( formBody.encodedName( x ),formBody.encodedValue( x ) );
                    temMap.put( formBody.encodedName( x ) ,formBody.encodedValue( x ));
                 }
              for(Map.Entry<String,String>entry:map.entrySet()){
                if(!temMap.containsKey( entry.getKey() )){
                    builder.add( entry.getKey(),entry.getValue() );
                }
              }
                 FormBody newformbody = builder.build();
                 Request newrequest = yuanlairequest.newBuilder()
                         .post( newformbody )

                         .build();
                 return chain.proceed( newrequest );
             }
         }
    }
    return chain.proceed( yuanlairequest );
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值