Kotlin Volley Android POST multipart / form-data

时间:2019-03-10 20:01:42

标签: curl kotlin android-volley

我具有以下功能,可以将GPS数据发送到我的odoo服务器。工作正常。但是当我尝试在凌空kotlin / androidstudio中执行此操作时,它不起作用。请帮忙。

curl -X POST -H"Content-Type: multipart/form-data" -F coordinates=[4.5232, -96.4242] url

这是到目前为止我尝试过的代码片段:

var lat: Float = intent.getFloatExtra("LATITUDE",0f)
var lng: Float = intent.getFloatExtra("LONGITUDE",0f)
val coordinatesRequest = object: JsonObjectRequest(Request.Method.POST,
                "http://url.com",
                null,
                Response.Listener<JSONObject>{response ->
                    Log.d(TAG,"Response: ${format(response.toString())}")

                },
                Response.ErrorListener { error ->
                    com.android.volley.VolleyLog.e(TAG,"/post request failed! Error: ${error.message}")
                }) {

                //override fun getBodyContentType(): String {
                    //return MULTIPART_FORMDATA
                //}

                override fun getBody(): ByteArray {
                    val params1 = HashMap<String, String>()
                    params1.put("coordinates","[$lat,$lng]")
                    val charset = Charsets.US_ASCII
                    //val map: List<String> = params.map {
                            //(key, value) -> "--$BOUNDARY\nContent-Disposition: form-data; name=\"$key\"\n\n$value\n"
                    //}
                    //val endResult = "${map.joinToString("")}\n--$BOUNDARY--\n"
                    return params1.toString().toByteArray(charset)
                }

                override fun getHeaders(): MutableMap<String, String> {
                    val headers = HashMap<String,String>()
                    headers.put("Content-Type","multipart/form-data")
                    return headers
                }

            }

            Log.d(TAG, "lo que envío: ${coordinatesRequest.body}")
            HttpRequestSingleton.getInstance(context.applicationContext).addToRequestQueue(coordinatesRequest)
        }

2 个答案:

答案 0 :(得分:0)

我在下面的curl命令中遇到了类似的问题-

curl 'https://ws.test.com/handle_email?embed_load_code=undefined' -H 'Accept: /' -H 'Referer: https://cdn1.test.com/widgets/12345/12345/widget.html' -H 'Origin: https://cdn1.test.com' -H 'User-Agent: Test App' -H 'DNT: 1' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' --data 'campaign=12345&merchant=12345&original_data=%257B%2522site%2522%253A%2522site-11111-www.test.com%2522%257D&share_id=&email=test%40test.com' —compressed

弄清楚如何组织对Volley Request的cUrl查询的不同部分的简便方法是,首先在Post Man中运行此cUrl查询,然后在Charles Proxy中拦截请求对象-参考:Simulate a specific CURL in PostMan

就我而言-

-H值被添加为标题项 -数据值作为正文添加 内容类型设置为application / x-www-form-urlencoded

答案 1 :(得分:0)

使用Content-Type:application / json