在android中使用okhttp将数组或jsonobject传递到php url?
我想通过android中的okhttp将两个值(只能是大括号中的数组或jsonobject)传递给php Web服务,如下所示:在android中使用okhttp将数组或jsonobject传递到php url?,php,android,json,web-services,okhttp,Php,Android,Json,Web Services,Okhttp,我想通过android中的okhttp将两个值(只能是大括号中的数组或jsonobject)传递给php Web服务,如下所示: userid=“1”&productid={“1”、“2”、“3”} 我知道如何通过okhttp传递userid,但我不知道如何通过userid将productid值传递给url。 如果它是一个重复请给我的链接,我已经试图搜索它,但没有找到任何相关的答案。 请帮忙。 提前感谢。//将对象转换为数组 //Convert your object to an a
- userid=“1”&productid={“1”、“2”、“3”}
//将对象转换为数组
//Convert your object to an array
FormBody.Builder formBuilder = new FormBody.Builder();
for(int x=0; x<array.length; x++)
{
String val = (String) array[x];
formBuilder.add("productid["+x+"]",val);
}
RequestBody body = formBuilder.build();
Request request = new Request.Builder()
.url(YOUR_URL)
.post(body)
.build();
FormBody.Builder formBuilder=新的FormBody.Builder();
对于(intx=0;xSee),您可以传递这个应答后面的数组的每个元素。您可以将该json对象转换为字符串,然后pass@RogerRV感谢您的回复…我已经检查了帖子,但是它会将parms发布为productid1=“1”、productid2=“2”、productid3=“3”…但是我希望所有这些参数都包含在一个参数中,比如productid={“1”、“2”、“3”}这可以是任何数组、arraylist、hashmap、jsonobject…@UdayNaidu您能详细说明您的答案吗请…任何代码..@ChiragGohil但如果您添加了像key productid[0]以值1为例,您将作为php中唯一的变量接收它。如果它是另一种类型,在传递之前,您可以将数据转换为数组,然后在每个数组元素中循环添加post中的所有元素format@ChiragGohil等一下,我会编辑答案,我知道这是不正确的我尝试过这个,但不工作,所以让我知道你更新答案。@ChiragGohil很抱歉,现在更新了。我是新使用okhttp的。我使用了其他类似于Volley的代码。代码运行良好,但仍然没有解决我的问题,因为我只需要一个变量和多个值……但非常感谢您的帮助。如果您找到更多内容,请发布…再次感谢…@ChiragGohil更新了答案
FormBody.Builder formBuilder = new FormBody.Builder();
//Check if object is HashMap
if(object instanceof HashMap)
{
for(Entry<String, String> e : m.entrySet()) {
String key = e.getKey();
String val = e.getValue();
formBuilder.add("productid["+key+"]",val);
}
} else if(object instanceof Array) {
for(int x=0; x<array.length; x++)
{
String val = (String) array[x];
formBuilder.add("productid["+x+"]",val);
}
}
RequestBody body = formBuilder.build();
Request request = new Request.Builder()
.url(YOUR_URL)
.post(body)
.build();
<?php
$productidstring = $_POST['productid'];
$productid = StringToArray($productidstring);
function StringToArray($productidstring)
{
$productidstringtmp = str_replace("[","",$productidstring);
$productidstringtmp = str_replace("]","",$productidstring);
$productidarray = explode(",",$productidstringtmp);
return $productidarray;
}
?>