OkHttp在android中用于发出网络请求 [英] OkHttp in android for making network requests
问题描述
我想做什么 ::
我正在尝试学习 Okhttp 在Android中进行网络通话
I am trying to learn the usage of Okhttp for making networking calls in android
我做了什么 ::
- I have read their documentation here
- I have downloaded and added the JAR in the project
- I am using their sample code from here
MyCode ::
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.internal.http.Request;
import com.squareup.okhttp.internal.http.Response;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Request request = new Request.Builder()
.url("https://raw.github.com/square/okhttp/master/README.md")
.build();
Response response = client.execute(request);
Log.d("ANSWER", response.body().string());
}
}
我正面临的错误 ::
行响应响应=客户端。执行(请求);
我收到错误:
In the line Response response = client.execute(request);
I am getting error as :
客户端无法解析变量
client cannot resolved to a variable
如何解决这个问题!
public class MainActivity extends Activity {
OkHttpClient client = new OkHttpClient();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Request request = new Request.Builder()
.url("https://raw.github.com/square/okhttp/master/README.md")
.build();
Response response = client.execute(request);
Log.d("ANSWER", response.body().string());
}
}
现在我是面临错误:
行中的
响应响应= client.execute(请求);
as方法execute(Request)未定义类型OkHttpClient
推荐答案
方法执行(请求)未定义类型OkHttpClient
The method execute(Request) is undefined for the type OkHttpClient
您收到此异常是因为没有这样的方法,即执行(请求
) OkHttpClient
。而是在调用
对象上调用,该对象是使用 OkHttpClient
对象获得的,如下所示:
You are getting this exception because there is no such method ie.execute(Request
) for OkHttpClient
. Rather it is invoked on Call
object which is obtained using OkHttpClient
object as follows:
Call call = client.newCall(request);
Response response = call.execute();
我认为你应该使用
Response response = client.newCall(request).execute();
而不是响应响应= client.execute(请求);
这篇关于OkHttp在android中用于发出网络请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!