用于测试 API 的 curl 命令 [英] Curl command to test the API

查看:23
本文介绍了用于测试 API 的 curl 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试以下规范的 API

I need to test an API of following spec

URL: http://myapp.com/api/upload/
Method: POST
Parameters: 
   image: (binary data of image)

returns
   a JSON Object

用于测试 api 的示例 php 实现

sample php implementation to test the api

<?php
$ch = curl_init();
$url = 'http://myapp.com/api/upload/';

$fields = array('image'=>file_get_contents('profile-pic.jpg'));

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_URL, $url);

$json = curl_exec($ch);
echo "\n".$json."\n";

?>

我使用 RESTClient 和 Poster 扩展来测试其他 api,我不确定如何使用这些工具为名为 image 的参数发送二进制数据.

I use RESTClient and Poster extensions to test other api, I'm not sure how to send binary data for a parameter named image with those tools.

如何使用 Curl 命令测试上述 api?

How do I test the above api using Curl command?

没有这个运气

curl -X POST --data-binary "image=@test.jpg" "http://myapp.com/api/upload/"

test.jpg 在当前目录中.我无法更改第 3 方 API,以便能够使用其他编码格式进行测试.

test.jpg is in current directory. I can't change the 3rd party API, to be able to test with other encoding formats.

推荐答案

curl -X POST --data-urlencode 'image@test.jpg' 'http://myapp.com/api/upload'

image@,不是image=@.

这是假设图像数据在发送之前进行了 urlencoded,这就是我认为 PHP 代码所做的.

This is assuming that the image data is urlencoded before sending, which is what I figure the PHP code does.

这篇关于用于测试 API 的 curl 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆