gpt4 book ai didi

java - Android okhttp : Getting randomly java.net.ProtocolException : Unexpected status line: 1. 1 200 OK

转载 作者:行者123 更新时间:2023-11-29 02:31:24 27 4
gpt4 key购买 nike

当使用 androids URL 和 HttpUrlConnection 向后端点发送 GET 请求时,有时(十分之一)会发生请求失败的原因:java.net.ProtocolException:意外的状态行:1.1 200 OK

如前所述,这种情况偶尔会发生,我尝试了 3 种不同的后端(其中一种是自托管的),但它仍然会发生。

        System.setProperty("http.keepAlive", "false");
URL url = new URL(callUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setConnectTimeout(5000);
con.setReadTimeout(4000);
con.setRequestMethod(requestMethod);
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("Connection", "close");

也许有人知道如何解决它?

最佳答案

First of all, this is the API references link: http://square.github.io/retrofit/

所以,去:File > Project Structure,打开后,在modules - app中,转到标签Dependencies

My Project Depedencies

点击+符号并添加库

搜索并添加此库:com.squareup.retrofit2:retrofit:2.30,我强烈建议您也使用 Jackson,如果需要,请将此库添加至:com .squareup.retrofit2:converter-jackson:2.3.0

完成所有依赖项和构建之后,让我们转到代码。

我用这段代码创建了一个RetrofitInitialization类:

public class RetrofitInicializador {
public RetrofitInitialization() {

String url = "localhost:8080/webservice/";
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(JacksonConverterFactory.create()).build();
}
}

我们也需要创建一个服务,所以,我创建了一个名为:对象服务

public interface ObjectService {

@POST("post/example")
Call<Object > postexemple(@Body Object object);

@GET("get/example/{id}")
Call<Object> getexemple(@Path("id") Integer id);

}

对象是您要接收或发送的模型。在此之后,将您的服务添加到构造函数之后的 RetrofitInitialization 中。

类似的:

public ObjectService getObjectService() {
return retrofit.create(ObjectService.class);
}

在您的 Activity 或任何您想获取此信息的地方,执行如下操作:

 private void loadFromWS(Object object) {
Call<Object> call = new RetrofitInicializador().getObjectService().postexemple(object);
call.enqueue(new Callback<Object>() {
@Override
public void onResponse(Call<Object> call, Response<Object> response) {
Object response = response.body();

// DO your stuffs
}

@Override
public void onFailure(Call<Object> call, Throwable t) {
Toast.makeText(AgendaActivity.this, "Connection error", Toast.LENGTH_SHORT).show();
}
});
}

编辑:忘记说了,我在 WS REST 服务器上使用了这个(更具体地说:JAX-RS 和 Jersey WS)

关于java - Android okhttp : Getting randomly java.net.ProtocolException : Unexpected status line: 1. 1 200 OK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49455329/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com