android 4.4 connection 报错,解决Android4.4及如下Volley框架Patch请求报错问题(Kotlin)...

import com.android.volley.toolbox.HttpStack

import com.android.volley.AuthFailureError

import com.android.volley.Request

import com.squareup.okhttp.MediaType

import com.squareup.okhttp.OkHttpClient

import com.squareup.okhttp.Protocol

import com.squareup.okhttp.RequestBody

import org.apache.http.HttpEntity

import org.apache.http.ProtocolVersion

import org.apache.http.entity.BasicHttpEntity

import org.apache.http.message.BasicHeader

import org.apache.http.message.BasicHttpResponse

import org.apache.http.message.BasicStatusLine

import java.io.IOException

import java.util.concurrent.TimeUnit

/**

* Created by Raleigh.Luo on 17/11/20.

* 解决Volley Patch请求在5.0如下不能使用的问题

* com.android.volley.NoConnectionError: java.net.ProtocolException: Unknown method 'PATCH'; must be one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE]

*/

class OkHttpStack : HttpStack {

private val mClient: OkHttpClient

constructor(client: OkHttpClient) {

this.mClient = client

}

@Throws(IOException::class, AuthFailureError::class)

override fun performRequest(request: Request?, additionalHeaders: MutableMap?): org.apache.http.HttpResponse {

val client = mClient.clone()

val timeoutMs = request?.getTimeoutMs()?.toLong()?:0L

client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS)

client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS)

client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS)

val okHttpRequestBuilder = com.squareup.okhttp.Request.Builder()

okHttpRequestBuilder.url(request?.getUrl())

val headers = request?.getHeaders()

headers?.keys?.let {

for (name in it) {

okHttpRequestBuilder.addHeader(name, headers.get(name))

}

}

additionalHeaders?.keys?.let {

for (name in it) {

okHttpRequestBuilder.addHeader(name, additionalHeaders[name])

}

}

setConnectionParametersForRequest(okHttpRequestBuilder, request!!)

val okHttpRequest = okHttpRequestBuilder.build()

val okHttpCall = client.newCall(okHttpRequest)

val okHttpResponse = okHttpCall.execute()

val responseStatus = BasicStatusLine(

parseProtocol(okHttpResponse.protocol()),

okHttpResponse.code(),

okHttpResponse.message()

)

val response = BasicHttpResponse(responseStatus)

response.setEntity(entityFromOkHttpResponse(okHttpResponse))

val responseHeaders = okHttpResponse.headers()

var i = 0

val len = responseHeaders.size()

while (i < len) {

val name = responseHeaders.name(i)

val value = responseHeaders.value(i)

if (name != null) {

response.addHeader(BasicHeader(name, value))

}

i++

}

return response

}

@Throws(IOException::class)

private fun entityFromOkHttpResponse(r: com.squareup.okhttp.Response): HttpEntity {

val entity = BasicHttpEntity()

val body = r.body()

entity.content = body.byteStream()

entity.contentLength = body.contentLength()

entity.setContentEncoding(r.header("Content-Encoding"))

if (body.contentType() != null) {

entity.setContentType(body.contentType().type())

}

return entity

}

@Throws(IOException::class, AuthFailureError::class)

private fun setConnectionParametersForRequest(builder: com.squareup.okhttp.Request.Builder, request: Request) {

when (request.getMethod()) {

Request.Method.DEPRECATED_GET_OR_POST -> {

// Ensure backwards compatibility.

// Volley assumes a request with a null body is a GET.

val postBody = request.getPostBody()

if (postBody != null) {

builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody))

}

}

Request.Method.GET -> builder.get()

Request.Method.DELETE -> builder.delete()

Request.Method.POST -> builder.post(createRequestBody(request))

Request.Method.PUT -> builder.put(createRequestBody(request))

Request.Method.HEAD -> builder.head()

Request.Method.OPTIONS -> builder.method("OPTIONS", null)

Request.Method.TRACE -> builder.method("TRACE", null)

Request.Method.PATCH -> builder.patch(createRequestBody(request))

else -> throw IllegalStateException("Unknown method type.")

}

}

private fun parseProtocol(p: Protocol): ProtocolVersion {

when (p) {

Protocol.HTTP_1_0 -> return ProtocolVersion("HTTP", 1, 0)

Protocol.HTTP_1_1 -> return ProtocolVersion("HTTP", 1, 1)

Protocol.SPDY_3 -> return ProtocolVersion("SPDY", 3, 1)

Protocol.HTTP_2 -> return ProtocolVersion("HTTP", 2, 0)

}

throw IllegalAccessError("Unkwown protocol")

}

@Throws(AuthFailureError::class)

private fun createRequestBody(r: Request): RequestBody? {

val body = r.body ?: return null

return RequestBody.create(MediaType.parse(r.bodyContentType), body)

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用: 根据提供的引用,是可以使用一行代码实现kotlinandroid4.4以上版本的沉浸式设计。具体示例代码如下: class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ... window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE } } 引用: 根据提供的引用,当在android4.4以下版本中使用volley请求发送PATCH请求时,会报错java.net.ProtocolException: Unknown method 'PATCH'. 这是因为在4.4以下的版本中,HTTP请求方法中不包含PATCH方法。可以考虑使用其他方法,如POST或PUT。 引用: 根据提供的引用,可以根据手机的Android版本选择使用不同的网络请求库。在5.0及以上版本,可以使用volley发送请求: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Volley.newRequestQueue(applicationContext).add(request) } 在5.0以下的版本,可以使用okhttp发送请求: if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { Volley.newRequestQueue(applicationContext, OkHttpStack()).add(request) } 请注意,以上代码仅供参考,具体实现还需要根据具体的需求和项目情况进行调整。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Immersive:一行代码实现沉浸式,适配android4.4到8.0+,沉浸式前所未有的简单](https://download.csdn.net/download/weixin_42144086/19051204)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [解决Android4.4及以下Volley框架Patch请求报错问题Kotlin)](https://blog.csdn.net/xiaoluoli88/article/details/78589214)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值