kotlin中请求和响应正文okhttp的参数是什么
我开始用okhttp3在kotlin中编写应用程序。我得到了回复,但是我怎么才能得到我需要的信息呢?例如,我使用。我只想知道“名字:”。我怎样才能告诉我的请求,我得到的只是“名字:”?你能提供一些代码示例或一些关于OkHTTP的说明和描述的源代码吗?我阅读了官方文件,但没有发现什么或只是不理解kotlin中请求和响应正文okhttp的参数是什么,kotlin,parameters,okhttp,Kotlin,Parameters,Okhttp,我开始用okhttp3在kotlin中编写应用程序。我得到了回复,但是我怎么才能得到我需要的信息呢?例如,我使用。我只想知道“名字:”。我怎样才能告诉我的请求,我得到的只是“名字:”?你能提供一些代码示例或一些关于OkHTTP的说明和描述的源代码吗?我阅读了官方文件,但没有发现什么或只是不理解 fun run(url: String){ val request = Request.Builder().url(url).build() //client.authen
fun run(url: String){
val request = Request.Builder().url(url).build()
//client.authenticator()
val client = OkHttpClient()
.newBuilder()
.addInterceptor { chain ->
val originalRequest = chain.request()
val builder = originalRequest
.newBuilder()
val name = request.header("name")
//.header("Authorization",
// Credentials.basic("login", "password"))
val newRequest = builder.build()
chain.proceed(newRequest)
}.build()
client.newCall(request).enqueue(object : Callback{
override fun onFailure(call: Call, e: IOException) {
toast("fail")
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
textView3.setText(response.body()?.string())
}
})
我试图使用.header(“name”)
,但它是红色的,我想我犯了一些错误。
感谢您的建议这里有一个使用Jackson ObjectMapper的方法 根据您的示例,假设您在响应中收到以下内容:
{
"login": "defunkt",
"id": 2,
"name": "Chris Wanstrath",
"company": null,
"blog": "http://chriswanstrath.com/"
}
但是您只对名称
字段感兴趣,因此您定义了一个用户
类:
公共类用户{private String name;}
然后使用配置为忽略缺少的属性的ObjectMapper
:
//content=response.body().string();
ObjectMapper mapper=新的ObjectMapper();
configure(在未知属性上反序列化feature.FAIL,false);
试一试{
User=mapper.readValue(content,User.class);
System.out.println(user.getName());//Chris Wanstath
}捕获(JsonProcessingException e){
e、 printStackTrace();
}
通常,API设计用于根据定义的模式提供响应。如果客户端应用程序在正文中接收到更多信息,则必须过滤掉不需要的部分,并仅使用响应中需要的部分。@sudipn您能帮助我如何过滤响应吗?我需要在标题中写入标记,如.header(“成功”)
或.header(“用户名”)
,对吗?