在python中进行开发时,如何在post请求中使用“format=json&data=”?

tjrkku2a  于 2023-03-04  发布在  Python
关注(0)|答案(5)|浏览(139)
format=json&data={
  "pickup_location": {
    "pin": "110096",
    "add": "address",
    "phone": "1111111111",
    "state": "Delhi",
    "city": "Delhi",
    "country": "India",
    "name": "name of pickup/warehouse location registered with delhivery"
  }
}

上面的数据是API文档所需的post的有效负载。
由于"format = json & data =",我不知道如何传输这些数据。
x一个一个一个一个x一个一个二个x
这是我试过的两段代码。
最终结果是一样的:* *"POST中缺少格式键"**。
我也在网上查过了,但是我找不到正确的答案。
所以我来找3Q帮忙。

8xiog9wr

8xiog9wr1#

我也遇到了同样的问题,实际上有效载荷是原始数据,所以这样做

payload = {
"pickup_location": {
    "pin": "110096",``
    "add": "Changsha",  # address of warehouse
    "phone": "1111111111",
    "state": "Delhi",
    "city": "Delhi",
    "country": "India"
}
}

payload = f'format=json&data={json.dumps(payload,default=str,indent=4)}'
response=requests.post(url_order,data=payload,headers=headers)
hfyxw5xn

hfyxw5xn2#

格式和数据密钥必须在正文x-www-form-urlencoded类型x1c 0d1x中发送

mrzz3bfm

mrzz3bfm3#

我穿春靴的时候也是这样。
当我开始寻找的时候
然后我发现了这个问题,我写这个答案为 Spring 启动开发人员。

    • Package **
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
    • 代码**
@Autowired
private RestTemplate restTemplate;

private HttpHeaders getHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Token yourToken");
    headers.set("Content-Type","application/json");
    return headers;
}

@Override
public Object save(ExpressDeliveryVO expressDelivery) throws JsonProcessingException {

    HttpHeaders headers = getHeaders();

    ObjectMapper mapper = new ObjectMapper();
    
    HttpEntity<String> entity = new HttpEntity<>("format=json&data="+mapper.writeValueAsString(expressDelivery), headers);
    
    return restTemplate
            .postForEntity("https://staging-express.delhivery.com/api/cmu/create.json", entity, Object.class)
            .getBody();

}
3pmvbmvn

3pmvbmvn4#

payload = {
    "pickup_location": {
        "pin": "110096",
        "add": "Changsha",
        "phone": "1111111111",
        "state": "Delhi",
        "city": "Delhi",
        "country": "India"
    }
}

payload = 'format=json&data={}'.format(payload).replace("'",'"')  # replace is very important
r = requests.post(url_test, json=payload, headers=headers)

Python字符串默认在外部使用双引号,在内部使用单引号,但是API要求参数键使用双引号。

laximzn5

laximzn55#

//这段代码在节点提取中运行良好

const option = {
method: 'POST',
headers: {
  Authorization: "Token " + apikey,
  accept: 'application/json',
  'Content-Type': 'application/json',
},
body: `format=json&data= ${JSON.stringify(createData)}`

}

相关问题