标签: okhttp

使用 okhttp3 调用测试方法

我在服务类中有一个方法可以调用外部 api。我将如何模拟这个 okHttpClient 调用?我尝试用mockito 这样做,但没有成功。

//this is the format of the method that i want to test
public string sendMess(EventObj event) {
    OkHttpClient client = new OkHttpClient();
    //build payload using the information stored in the payload object
    ResponseBody body = 
        RequestBody.create(MediaType.parse("application/json"), payload);
    Request request = //built using the Requestbody
    //trying to mock a response from execute
    Response response = client.newCall(request).execute();
    //other logic
}
Run Code Online (Sandbox Code Playgroud)

如果有助于测试,我愿意重构服务类。如有任何建议和推荐,我们将不胜感激。谢谢。

java unit-testing mocking okhttp spring-boot

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

Retrofit 不会序列化我的响应类中的第二个对象

我的问题是,当使用发布 APK 运行我的应用程序(启用了 proguard)时,GSON 不会序列化我的第二个对象。第一个对象已成功序列化。但是,应用程序在调试模式下运行一切都很好。

我的应用程序使用 Retrofit2.6 和 Proguard。Gradle版本是gradle:3.5.1

我来自 WebServer 的 json 数据

 {
  "error": false,
  "contents": [
    {
      "id": 1,
      "channel": {
        "id": 7,
        "language_id": 1
      },
      "publisher": {
        "id": 1,
        "name": "Name of Publisher"
      },
      "title": "Some title",
      "description": "This is description",
      "subscribed": false
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

这是 Retrofit 的 Response 类

public class GetContentsResponse{

    @SerializedName("error")
    @Expose
    private boolean mError;

    @SerializedName("contents")
    @Expose
    private List<Content> mContents;

}

public class Content {

    @SerializedName("id")
    @Expose
    private int mId;

    @SerializedName("channel")
    @Expose …
Run Code Online (Sandbox Code Playgroud)

android proguard gson okhttp retrofit2

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

OkHttpInterceptor 从 kotlin 拦截器导航到登录片段

我在这里有点挣扎。

我想要实现的是,如果发生 401,则从 Httpinterceptor 导航回登录片段。

我使用 Jwt 进行授权,如果令牌不再有效,后端将返回 401 未经授权。

我尝试用谷歌搜索这个问题,但最终没有真正解决我的问题。

到目前为止,我尝试做的是通过 NavHostFragment.findNavController 和 findNavController(MainActivity.activity, 1) 获取导航控制器。

这两件事都不起作用,因为第一个要求您提供拦截器中没有的片段,而第二个则失败,因为我无法找到从拦截器访问 MainActivity 的方法。

没有太多代码,但这就是拦截器现在的样子(由于明显的原因而不起作用)

package de.wabi.vistascraper.library.http.interceptors

import androidx.navigation.Navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import de.wabi.vistascraper.MainActivity
import de.wabi.vistascraper.ui.main.MainFragment
import okhttp3.Interceptor
import okhttp3.Response

class ErrorInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var builder = chain.request().newBuilder()

        var response = chain.proceed(builder.build())

        var test = NavHostFragment.findNavController(this.);

        if(response.code == 401){
           // var test = findNavController(MainActivity.activity, 1)

        }
        return response;
    }
}
Run Code Online (Sandbox Code Playgroud)

也许互联网上的你们有一个想法。

提前致谢

大卫

android interceptor kotlin okhttp android-jetpack-navigation

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

如何使用 MOSHI 将 json 字符串解析为列表

我正在解析下面的 JSON:

{
  "list": [
    {
      "data1": "data1",
      "transaction": {
        "data2": "data2",
        "data3": "data3"
      },
      "breakdowns": [
        {
          "data4": "data4",
          "data5": "data5"
        }
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我使用 Moshi 和 okHttpClient 来处理这个 JSON。我的数据类是正确的

但是当我尝试如下解析它时:

val moshi = Moshi.Builder()
  .add(KotlinJsonAdapterFactory())
  .build()

val type = Types.newParameterizedType(List::class.java,PaymentRequest::class.java)

try{
   val q = moshi.adapter(type)
   paymentRequest = q.fromJson(response.body!!.source())!!
} catch (e: Exception) {
   println(e)
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $

android kotlin okhttp moshi

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

如何在标准java程序中导入okhttp?

我正在尝试在java程序中导入okhttp包,但我一直无法找到如何做到这一点。

目前,我已将包下载到我的计算机上(从以下 git hub 链接: https: //github.com/square/okhttp),但我不明白如何在我的程序中导入包。

关于如何使用这个包有什么建议吗?

java okhttp

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

如何模拟特定的 URL 路径?

我在测试期间使用 okhttp 来模拟我的 http 响应。

//Create a mock server
mockWebServer.start(8080)
mockWebServer.enqueue(MockResponse().setBody("").setResponseCode(HttpURLConnection.HTTP_OK))
Run Code Online (Sandbox Code Playgroud)

然而,这对每条路径的响应都是OK。

如何模拟特定的 url 而不是全部?

okhttp mockwebserver

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

如何使用okhttp禁用SSLv3后备

我的android应用程序依赖于SNI来访问正确的服务器,因此它需要TLS并且不能与SSLv3一起使用.我正在使用okhttp和改造,服务器日志表明突然TLS握手切换到SSLv3并可能保持这种状态一段时间,导致由于缺少服务器名称指示支持而导致重复的主机名验证失败.

我知道在某些情况下(哪些?)okhttp停止使用TLS并切换到SSL作为后备.但是,这在SNI的情况下是不可接受的,有没有办法禁用回退?

示例apache日志:

[Wed May 07 18:00:12.799511 2014] [ssl:debug] [pid 20369:tid 140532403599104] ssl_engine_kernel.c(1891): [client <removed>:51431] AH02041: Protocol: TLSv1, Cipher: RC4-SHA (128/128 bits)
[Wed May 07 18:00:28.563170 2014] [ssl:debug] [pid 20455:tid 140532646553344] ssl_engine_kernel.c(1891): [client <removed>:51432] AH02041: Protocol: TLSv1, Cipher: RC4-SHA (128/128 bits)
[Wed May 07 18:00:45.884075 2014] [ssl:debug] [pid 20371:tid 140532445562624] ssl_engine_kernel.c(1891): [client <removed>:51433] AH02041: Protocol: TLSv1, Cipher: RC4-SHA (128/128 bits)
[Wed May 07 18:01:01.322657 2014] [ssl:debug] [pid 20455:tid 140532395206400] ssl_engine_kernel.c(1891): [client <removed>:51434] AH02041: Protocol: TLSv1, Cipher: RC4-SHA (128/128 bits)
[Wed …
Run Code Online (Sandbox Code Playgroud)

ssl android square sni okhttp

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

java okhttp动态地使用for循环添加头文件

许多例子显示添加标题应该:

Request request = new Request.Builder()
    .url("https://api.github.com/repos/square/okhttp/issues")
    .header("User-Agent", "OkHttp Headers.java")
    .addHeader("Accept", "application/json; q=0.5")
    .addHeader("Accept", "application/vnd.github.v3+json")
    .build();
Run Code Online (Sandbox Code Playgroud)

但我想动态添加标题作为用户的标题要求,我该如何实现它?

Headers h = new Headers.Builder().build();
for (HttpHeader hh : ht.HttpRequestHeader) {
    h.newBuilder().add(hh.Name, hh.Value);
}  //<<---Nothing changed!!!!!
Run Code Online (Sandbox Code Playgroud)

java http-headers okhttp okhttp3

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

如何在squareup.okhttp3中缓存响应

我试图通过OKhttp缓存http响应,但无法找到一些好的示例或文档.

谢谢你的帮助

java android caching okhttp

3
推荐指数
2
解决办法
4382
查看次数

检查互联网连接OKHTTP

我使用以下代码进行api调用,并根据收到的响应将用户定向到页面.我如何检查互联网连接?

我正在使用一个OK HTTP客户端,我的代码如下所示:

 button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String url = "https://xxxxxxxx/" + orderLineId;
            JSONObject jSon = new JSONObject();
            try {
                jSon.put("prescription_xxxxx", prescriptionIntervalId);
                jSon.put("prescription_xxxxxxx", false);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String data = jSon.toString();
            RequestBody body = RequestBody.create(JSON, data);
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", token)
                    .addHeader("Accept", "application/json")
                    .put(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {@Override
                public void onFailure(Request request, IOException e) {

                    AlertDialog.Builder dialog = new AlertDialog.Builder(AutoRefillActivity.this);
                    dialog.setMessage("Something went wrong. Check connection.")
                            .setCancelable(false) …
Run Code Online (Sandbox Code Playgroud)

java https android android-studio okhttp

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