android adt 网络请求

一、导入控件
我使用的是 xutils2.6.14,导入方法如下,下载 xutils2.6.14(下载地址:)到目录libs下

在app文件夹下的 build.gradle 文件添加如下依赖项:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.1'

    # 关键是这个
    compile files('libs/xUtils-2.6.14.jar')

    compile 'com.google.android.gms:play-services-appindexing:8.1.0'
}

至此,再将页面切换到对应的java文件,此时会弹出是术 “sync now” 点中即可

二、网络请求示例
直接上代码

private void test() {
        //请求参数定义
        RequestParams params = new RequestParams();        
        params.addBodyParameter("index", "1");
        params.addBodyParameter("param1", "test);

        HttpUtils https = new HttpUtils();
        https.configCurrentHttpCacheExpiry(2000);
        //此为请求地址,根据具体定义
        String url = "https://www.baidu.com";
        HttpHandler<String> send =  https.send(HttpRequest.HttpMethod.POST, url, params,
                new RequestCallBack<String>() {

        @Override
        public void onFailure(HttpException error, String msg) {
        //失败
        LogUtil.logcat(Constants.SERVICE_DATASOURCE + ":" + "读取启动图片错误,错误信息:" + msg + "\r\n异常信息:" + error.toString());
        }

        @Override
        public void onSuccess(ResponseInfo<String> responseInfo) {
            //请求成功
            if(responseInfo == null){
                LogUtil.logcat(Constants.SERVICE_DATASOURCE + ":" + "responseInfo is null");
            }else { 
                LogUtil.logcat(Constants.SERVICE_DATASOURCE + ":" + responseInfo.result);
            }
    }
    );
}

三、过程中出现的问题
在写好代码,连接好编译器后,点运行,上报如下错误

 Error:(57, 58) 错误: 无法访问HttpRequestBase
 找不到org.apache.http.client.methods.HttpRequestBase的类文件

解决方法:在app下的build.gradle 中的 android 子集中新增依赖,如下所示

android{
.... 略
useLibrary 'org.apache.http.legacy'
}

以后再运行,一切OK。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章