square - okhttp - OkHttpClient无法解析

时间:2016-01-15 17:01:50

标签: java android

目前我正在研究Stormy Treehouse Android app。我想使用square OkHttpClient但我收到错误"无法解析符号okhttp3"导入课程时:import com.squareup.okhttp3.OkHttpClient;。用okhttp替换okhttp3并不能解决错误。谢谢你的帮助。

MainActivity.java

package com.trainerworkout.stormy;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

// cannot resolve symbol 'okhttp3'
import com.squareup.okhttp3.OkHttpClient;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        String apiKey = "f9d033c3cdeab16b95cecdeb6721a093";
        double latitude = 45.5124;
        double longitude = -73.5547;
        String forecastUrl = "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude;
        // Cannot resolve symbol
        OkHttpClient client = new OkHttpClient();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    } // onCreate()
} // MainActivity

build.gradle(Module:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.trainerworkout.stormy"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.squareup.okhttp3:okhttp:3.0.1'
}

3 个答案:

答案 0 :(得分:10)

尝试删除导入,然后转到此行

OkHttpClient client = new OkHttpClient();

将光标移至OkHttpClient并按Alt + Enter,您将看到2个类可供选择导入,如下图所示:

1

所以基本上有两种类型的可用导入

1)。 import com.squareup.okhttp.OkHttpClient;

2)。 import okhttp3.OkHttpClient;

和你的没有匹配,请尝试导入正确的,具体取决于您的要求。

答案 1 :(得分:1)

我也面临同样的问题,请尝试更改gradle中的依赖关系。

**

依赖项{

compile fileTree(dir: 'libs', include: ['*.jar'])
compile files('libs/okhttp-3.4.2.jar')
compile 'com.squareup.okhttp3:okhttp:3.4.2'
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.1'
testCompile 'junit:junit:4.12'

}

**

答案 2 :(得分:0)

您必须在build.gradle(app)中添加这两个依赖项:

编译'com.squareup.okhttp:okhttp:2.2.0'

编译'com.squareup.okhttp:okhttp-urlconnection:2.0.0'

之后,您将能够完美地安装应用程序。