标签: okhttp

Retrofit2 204 No Content 有内容异常

我从服务器获得空 json (“{}”) 作为删除响应,代码为 204。

okhttp3.internal.http.HttpEngine课堂上,有一个令人讨厌的事情被抛出:

  if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
    throw new ProtocolException(
        "HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
  }
Run Code Online (Sandbox Code Playgroud)

如果您尝试返回标头中没有内容(服务器端)的内容,内容长度仍然大于 0;

任何非服务器端的想法如何解决这个问题?

android okhttp retrofit2

1
推荐指数
1
解决办法
4394
查看次数

拦截器没有被称为retrofit2

尝试添加拦截器以使用 okhttp3 和 Retrofit2 向请求添加标头。我注意到标头没有添加到请求中,并且我的 system.out.println 调试行从未被调用。不知道为什么,但这是我的代码:

创建服务:

OkHttpClient client = new OkHttpClient();

        client.newBuilder()
                .addInterceptor(new ServiceInterceptor(context))
                .authenticator(new MyAuthenticator(context))
                .build();

        service = (new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build())
                .create(Service.class);
Run Code Online (Sandbox Code Playgroud)

服务拦截器:

public class ServiceInterceptor implements Interceptor {

    private final Context context;

    public ServiceInterceptor(Context context){
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        System.out.println("Interceptor");

        if(request.header("No-Authentication") == null){
            request = request.newBuilder()
                    .addHeader("User-Agent", "APP NAME")
                    .addHeader("Authorization", "bearer " + PreferenceManager.getDefaultSharedPreferences(context).getString("access_token", ""))
                    .build();
        }

        return chain.proceed(request);
    }
} …
Run Code Online (Sandbox Code Playgroud)

java android okhttp retrofit2

1
推荐指数
1
解决办法
2386
查看次数

我应该将哪个版本的 okhttp 和 okhttp 日志记录拦截器与 Retrofit 2.1.0 一起使用以避免此错误?

运行改造应用程序时出现以下错误:

E/AndroidRuntime:致命异常:OkHttp 调度程序进程:fr.univ_lehavre.greah.naoderapp,PID:20894 java.lang.NoSuchMethodError:类 Lokhttp3/internal/Platform 中没有虚拟方法日志(Ljava/lang/String;)V;或其超类('okhttp3.internal.Platform' 声明出现在 /data/app/fr.univ_lehavre.greah.naoderapp-2/split_lib_dependency_apk.apk 中)位于 okhttp3.logging.HttpLoggingInterceptor$Logger$1.log(HttpLoggingInterceptor.java :108)在okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:157)在okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:190)在okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)在okhttp3.RealCall .access$100(RealCall.java:30) 在 okhttp3.RealCall$AsyncCall.execute(RealCall.java:127) 在 okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 在 java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 在 java.lang.Thread.run(Thread.java:761)

这是我创建改造对象的类:

public class RetrofitImpl {

private static Retrofit retrofit = null;
public static final String BASE_URL = "http://192.168.43.144:8080/";
//    public static final String BASE_URL = "http://10.0.2.2:8080/";

public static Retrofit getClient() {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();
    return retrofit;
}
Run Code Online (Sandbox Code Playgroud)

}

我不确定应该使用哪个版本。

这些是我目前正在使用的:

implementation …
Run Code Online (Sandbox Code Playgroud)

rest android retrofit okhttp

1
推荐指数
1
解决办法
2506
查看次数

Android Api (Okhttps) 在 android 9(pie) 及更高版本中未被调用

我以与其他版本的手机相同的方式调用 android API,并且在 Oreo 版本即 8 之前工作正常。但在 android 9 即派版本及更高版本中不会调用该 API。如果馅饼有任何变化,请告诉我。提前致谢。

 private void getLoginAPI(String username, String password, String compnaycoce) {

    if (NetworkStatus.isNetworkConnected(this)) {
        LoginReqBean bean = new LoginReqBean();
        bean.UserId = username;
        bean.Password = password;
        bean.Company = compnaycoce;
        NetworkService serviceCall = new NetworkService(Constants.loginPost(), Constants.TAG_POST, this);
        serviceCall.call(bean);
    } else
        Toast.makeText(this, "Please check Internet connection", Toast.LENGTH_SHORT).show();
}

@Override
public void onNetworkCallInitiated(String service) {
    progressDialog = ProgressDialog.show(LoginActivity.this, "Info", "Validating Credentials, Please wait...");
    progressDialog.show();

}

 @Override
  public void onNetworkCallCompleted(String service, String response) {
    Log.e("LOGIN JSON …
Run Code Online (Sandbox Code Playgroud)

api android asynchronous android-asynctask okhttp

1
推荐指数
1
解决办法
2652
查看次数

okhttp 有计划使用异步套接字实现 http2 吗?

OkHttp 似乎在其 http2 实现中使用阻塞 I/O 和每个流一个线程。

okhttp 有计划使用异步套接字实现 http2 吗?

nio okhttp http2

1
推荐指数
1
解决办法
483
查看次数

如何解决:无法从network_security_config解析XML配置

我正在尝试使用 okhttp 从 api 获取 json,当我尝试这样做时,应用程序崩溃了,并且出现运行时异常

\n\n

Failed to parse XML configuration from network_security_config

\n\n

我应该怎么做才能解决这个问题?\ni 在我的清单上拥有互联网权限。\ni\'v 试图在其他问题上搜索类似的内容,但找不到答案。

\n\n

我尝试按照本教程进行操作:https://www.youtube.com/watch ?v=53BsyxwSBJk

\n\n

但 XML 似乎有一些问题,但我不明白。

\n\n

这是我的班级:

\n\n
class TestActivity : AppCompatActivity() {\n\n  override fun onCreate(savedInstanceState: Bundle?) {\n    super.onCreate(savedInstanceState)\n    setContentView(R.layout.activity_test)\n\n    val adapter = ArrayAdapter<User>(this, android.R.layout.simple_list_item_1)\n\n    listViewTest.adapter = adapter\n    val url = URL(myapi)\n\n    val request = Request.Builder().url(url).build()\n    val client = OkHttpClient()\n    client.newCall(request).enqueue(object: Callback {\n\n        override fun onResponse(call: Call, response: Response) {\n\n            val body = response.body.toString()\n\n            println(body)\n\n\n        }\n\n\n        override fun onFailure(call: …
Run Code Online (Sandbox Code Playgroud)

android kotlin okhttp

1
推荐指数
1
解决办法
8970
查看次数

迁移到androidX后,发布版本中的OkHttp帖子内容为空

在迁移到 androidX 之前,发布版本适用于每个 HTTP 请求。

迁移到 androidX 后,每个GET请求都有效,但所有POST请求都无效。它无法向服务器端发送参数。POST请求的所有内容都是空的。

我所做的唯一更改是将此项目迁移到 androidX。

我不确定在哪里可以找到更多的见解... :(

[更新]:通过kushan评论推荐添加接口和POJO :)

界面

@POST("/api/preference")
Call<RoasterPreference> updatePreference(@Body RoasterPreference roasterPreference);
Run Code Online (Sandbox Code Playgroud)

POJO 对象

import com.google.gson.annotations.SerializedName;

public class RoasterPreference {

  @SerializedName("type")
  private String type;

  @SerializedName("value")
  private String value;

  public RoasterPreference(String _type,String _value){

    type = _type;
    value = _value;
  }
} 
Run Code Online (Sandbox Code Playgroud)

来自调试版本的 OkHttp 日志:

D/OkHttp: --> POST http://192.168.0.1:9999/api/preference
Content-Type: application/json; charset=UTF-8
Content-Length: 29
{"type":"t_unit","value":"0"}
--> END POST (29-byte body)
Run Code Online (Sandbox Code Playgroud)

发布版本中的 OkHttp 日志:

D/OkHttp: --> POST …
Run Code Online (Sandbox Code Playgroud)

android android-studio okhttp retrofit2 androidx

1
推荐指数
1
解决办法
857
查看次数

OkHttp 添加基本认证头

我想将基本身份验证标头添加到我使用 OkHttp3 完成的请求中。

这是我的代码:

        // Adding Authentication Header
        OkHttpClient.Builder client = new OkHttpClient.Builder();
        client.authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                String credential = Credentials.basic(username, password);
                return response.request().newBuilder().header("Authorization", credential).build();
            }
        });

        // 
        client.connectTimeout(10, TimeUnit.SECONDS);
        client.writeTimeout(10, TimeUnit.SECONDS);
        client.readTimeout(10, TimeUnit.MINUTES);

        RequestBody body = RequestBody.create(null, new byte[]{});
        if( json != null) {
            body = RequestBody.create(MediaType.parse(
                    "application/json"),
                    json.toString()
            );
        }

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.build().newCall(request).enqueue(callback);
Run Code Online (Sandbox Code Playgroud)

不幸的是没有添加身份验证标头,我真的找不到错误。

android okhttp

1
推荐指数
1
解决办法
1815
查看次数

从改造 2.6.2 更新到改造 2.9.0 后 OkHttpClient.Builder() 中的 java.lang.NoSuchMethodError

早些时候,我在我的项目中使用改造版本 2.6.2来调用 api 服务,一切正常。我正在创建一个自定义Interceptor添加api key到每个请求的标头。

网络拦截器.kt

class NetworkInterceptor() : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        var request = chain.request()
            request = request.newBuilder()
                .addHeader("Authorization", "Client-ID ${NetworkConfig.CLIENT_ID}")
                .build()

        return chain.proceed(request)
    }
}
Run Code Online (Sandbox Code Playgroud)

我改装库更新到版本2.9.0和更新后改装版本2.9.0我收到java.lang.NoSuchMethodError该行OkHttpClient.Builder()同时加入InterceptorRetrofit.Builder()

api.kt

interface Api {

    @GET("photos")
    suspend fun getPhotos(
        @Query("page") pageNumber: Int,
        @Query("per_page") pageSize: Int,
        @Query("order_by") orderBy: String
    ) : Response<List<Photo>>

    @GET("photos/random")
    suspend fun getRandomPhoto() : Response<Photo>

    companion object{ …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-studio okhttp retrofit2

1
推荐指数
1
解决办法
516
查看次数

Okhttp 无法连接到本地主机端点抛出连接失败:ECONNREFUSED(连接被拒绝)

我正在尝试使用 okhttp 和 Flask 将本地后端和前端连接在一起,但是我收到 java.net.ConnectException: failed to connect to /127.0.0.1 (port 5000) after 10000ms: isConnected failed: ECONNREFUSED (Connection Dockered)例外

现在 API 确实可以正常工作,因为我可以在邮递员中访问它并返回值,这是代码

from flask import request, Flask
import getMovie
import getUser

api = Flask(__name__)

#Movie Endpoints

@api.route('/Movies/GetMovieById', methods=['GET'])
def get_movie_by_id():
    id = str(request.args['id'])
    return getMovie.getById(id)


@api.route('/Movies/All', methods=['GET'])
def get_all_movies():
    return getMovie.getAll()

#User Endpoints

@api.route('/Users/All', methods=['GET'])
def get_all_users():
    return getUser.getAll()

@api.route('/Users/GetUserById', methods=['GET'])
def get_user_by_id():
    id = str(request.args['id'])
    return getUser.getById(id)


if __name__ == '__main__':
    api.run()
Run Code Online (Sandbox Code Playgroud)

然后这是 Android 应用程序的主要活动

package com.example.moviebuffs

import …
Run Code Online (Sandbox Code Playgroud)

python android flask kotlin okhttp

1
推荐指数
1
解决办法
3443
查看次数