Android OkHttp网络请求 get 和 post (带Token)

Android OkHttp网络请求 get 和 post (带Token)

 

例:(打印)

Android OkHttp网络请求 get 和 post (带Token)_第1张图片

 

依赖:

    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.2'
    compile 'net.qiujuer.common:okhttp:3.0.0'
    compile 'com.google.code.gson:gson:2.2.4'

 



/**
 * Android OkHttp网络请求
 * get 和 post (带Token)
 */
public class MainActivity extends AppCompatActivity {

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

        setget();
        setpost();

    }



    /**
     * post请求
     * http://www.lygjjdj.com:82/HZZHDJ/api/base64Upload.do?base64String=data:image/png;base64,......
     * token : 2413a775f7d3fcfa0ebb625ac4e8ac35
     */
    public void setpost() {
        //post请求 传参
//        FormBody formBody = new FormBody.Builder()
//                .add("base64String","data:image/png;base64,"+imgStr)
//                .add("id","15")
//                .add("name","这是")
//                .build();

        Request request = new Request.Builder()
//                .url("http://www.lygjjdj.com:82/HZZHDJ/api/base64Upload.do")
                .url("http://www.lygjjdj.com:82/HZZHDJ/api/getMyInformation.do")
                .addHeader("token","847f1f8f0bde740400212d783942a753")
//                .post(formBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                Log.d("111111post请求失败======","e.getMessage()"+e.getMessage());
            }

            public void onResponse(Call call, Response response) throws IOException {
                //请求成功返回结果
                //如果希望返回的是字符串
                final String responseData=response.body().string();
                // 如果希望返回的是inputStream,有inputStream我们就可以通过IO的方式写文件.
//                InputStream responseStream=response.body().byteStream();
                // 注意,此时的线程不是ui线程,
                // 如果此时我们要用返回的数据进行ui更新,操作控件,就要使用相关方法
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        // Log.d("111111请求成功======",responseData );
                        Bean bean = new Gson().fromJson(responseData, Bean.class );
                        Log.d("111111post请求成功======","getHeadImg"+bean.getData().getHeadImg());
                        Log.d("111111post请求成功======","getHeadImg"+bean.getData().getLoginName());
                    }
                });
            }
        });

    }


    /**
     * get请求
     * http://www.lygjjdj.com:82/HZZHDJ/api/base64Upload.do?base64String=data:image/png;base64,......
     * token : 2413a775f7d3fcfa0ebb625ac4e8ac35
     */
    public void setget() {
        String url = "http://www.lygjjdj.com:82/HZZHDJ/api/getMyInformation.do?";
//                "&name=" + mine_02.getText().toString() +
//                "&phone=" + mine_03.getText().toString() +
//                "&address=" + mine_04.getText().toString() +
//                "&headImg=" + imgsrc;

        Request.Builder builder = new Request.Builder()
                .url( url )
                .addHeader( "token", "847f1f8f0bde740400212d783942a753" );
        Request build = builder.build();

        OkHttpClient client = new OkHttpClient.Builder().readTimeout( 5000, TimeUnit.SECONDS ).build();
        Call call = client.newCall( build );
        call.enqueue( new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("111111get请求失败======","e.getMessage()"+e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功返回结果
                //如果希望返回的是字符串
                final String responseData=response.body().string();
                //如果希望返回的是inputStream,有inputStream我们就可以通过IO的方式写文件.
//                InputStream responseStream=response.body().byteStream();
                //注意,此时的线程不是ui线程,
                // 如果此时我们要用返回的数据进行ui更新,操作控件,就要使用相关方法
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的操作
                        // Log.d("111111get请求成功======",responseData );
                        Bean bean = new Gson().fromJson(responseData, Bean.class );
                        Log.d("111111get请求成功======","getHeadImg"+bean.getData().getHeadImg());
                        Log.d("111111get请求成功======","getHeadImg"+bean.getData().getLoginName());
                    }
                });
            }
        });
    }

}

 

 

 

 

 

 

送上我常用依赖(vvvvv这些和上面的代码无关vvvvv):有问题欢迎来质询


    //圆形图片依赖:(一般和glide一起用):
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    //图片依赖比 imagerloader 更方便:
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    implementation 'com.facebook.fresco:fresco:+'

    // rxjava2 + retrofit2 + okhttp + gson
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.1.0'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-scalars:+'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.2'
    compile 'net.qiujuer.common:okhttp:3.0.0'
    compile 'com.google.code.gson:gson:2.2.4'

 

public class MyApp extends Application {
    
//    public static String registrationId ;//获取 极光推送的设备唯一性标识 RegistrationID


//    // 这是为了打印retrofit的log日志
//    //打印retrofit日志
//    public static HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger(){
//        @Override
//        public void log(String message) {
//            //打印retrofit日志
//            Log.i("RetrofitLog","retrofitBack = " + message);
//        }
//    });


    @Override
    public void onCreate() {
        super.onCreate();
        
        // Fresco 图片
        Fresco.initialize(this);

//        // 对log 的初始化
//        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);


//        //极光推送
//        JPushInterface.setDebugMode(true); 	// 设置开启日志,发布时请关闭日志
//        JPushInterface.init(this);  // 初始化 JPush
//        registrationId = JPushInterface.getRegistrationID(this);//获取 极光推送的设备唯一性标识 RegistrationID
//        Log.e("111111registrationId", "run:--------->:" + registrationId );
    }
}

 

 

 

 

你可能感兴趣的:(项目开发,网络请求工具类)