我正在编写一个删除API的服务器的客户端代码.API规范要求发送数据.我正在使用HttpComponents v3.1库来编写客户端代码.使用HtpDelete类我找不到向它添加请求数据的方法.有办法吗?以下是代码段.
HttpDelete deleteReq = new HttpDelete(uriBuilder.toString());
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair(RestConstants.POST_DATA_PARAM_NAME,
postData.toString()));
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
//deleteReq.setEntity(entity); // There is no method setEntity()
deleteReq.setHeader(RestConstants.CONTENT_TYPE_HEADER, RestConstants.CONTENT_TYPE_HEADER_VAL);
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException: " + e);
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
我正在使用.NET 4.0的ASP.NET Web API客户端库(Microsoft.AspNet.WebApi.Client版本4.0.30506.0).
我需要发送一个带有请求体的HTTP DELETE.我把它编码如下:
using (var client = new HttpClient())
{
client.BaseAddress = Uri;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// I would normally use httpClient.DeleteAsync but I can't because I need to set content on the request.
// For this reason I use httpClient.SendAsync where I can both specify the HTTP DELETE with a request body.
var request = new HttpRequestMessage(HttpMethod.Delete, string.Format("myresource/{0}", sessionId))
{
var data = new Dictionary<string, object> {{"some-key", "some-value"}};
Content = new ObjectContent<IDictionary<string, object>>(data, new JsonMediaTypeFormatter())
}; …Run Code Online (Sandbox Code Playgroud) 我发现了Spring MVC的一个非常奇怪的行为.
我有控制器方法:
@RequestMapping (value = "/delete/{id:.*}", method = RequestMethod.DELETE)
public ResponseEntity<Response> delete(@PathVariable (value = "id") final String id) {
HttpStatus httpStatus = HttpStatus.OK;
final Response responseState = new Response( ResponseConstants.STATUS_SUCCESS );
try {
POJO pojo = mediaFileDao.findById( id );
if (pojo != null) {
delete(pojo);
} else {
httpStatus = HttpStatus.NOT_FOUND;
responseState.setError( "NOT_FOUND" );
}
} catch (Exception e) {
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
responseState.setError( e.getMessage() );
}
return new ResponseEntity<>( responseState, httpStatus );
}
Run Code Online (Sandbox Code Playgroud)
所以,问题是当id包含点(例如"my_file.wav")时,Spring在任何情况下都会返回HTTP 406,但是如果id不包含点,则Spring会按照我的方式返回responseState(作为json).我尝试以不同的方式修复它(添加@ResponseBody,更改jackson版本,将Spring降级到4.0)但没有任何结果.
谁能帮我?
更新我为Spring …
我想使用python请求模块执行HTTP DELETE,该模块遵循以下API;
https://thingspeak.com/docs/channels#create
DELETE https://api.thingspeak.com/channels/4/feeds
api_key=XXXXXXXXXXXXXXXX
Run Code Online (Sandbox Code Playgroud)
我正在使用python v2.7并请求模块.我的python代码看起来像这样;
def clear(channel_id):
data = {}
data['api_key'] = 'DUCYS8xufsV613VX'
URL_delete = "http://api.thingspeak.com/channels/" + str(channel_id) + "/feeds"
r = requests.delete(URL_delete, data)
Run Code Online (Sandbox Code Playgroud)
代码不起作用,因为requests.delete()只能接受一个参数.正确的代码应该如何?
我需要使用REST API删除共享点列表中的所有项目。
我该如何实现?
我可以使用“ / _api / web / lists / getByTitle('MyList')/ items('ID')“删除单个项目
我试图删除该ID,但无法正常工作。
我正在使用expressjs和body-parser中间件.
这就是我发起它的方式:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Run Code Online (Sandbox Code Playgroud)
从客户端我发送DELETE请求,当我尝试从服务器端提取它时,我得到一个空对象:
app.delete('/', function(req, res) {
console.log(util.inspect(req.body)); //outputs {}
//some more code
});
Run Code Online (Sandbox Code Playgroud)
但是当我发送POST时,我得到了我需要的东西:
app.post('/delete', function(req, res) {
console.log(util.inspect(req.body)); //outputs { mid: 'ffw1aNh2' }
//some more code
});
Run Code Online (Sandbox Code Playgroud)
值得注意的是,我没有在客户端更改任何内容(angularjs),但方法和url以及firefox网络调试器显示在两种情况下发送的数据.
这里缺少什么?为什么我在删除方法上获得一个空体对象?
嘿,所以POST/PUT请求就这么做了
$http.post(url, body, headers)
Run Code Online (Sandbox Code Playgroud)
工作得很好
但是使用DELETE它会得到我的身体,但完全忽略了我的标题......
$http.delete(url, body, headers)
Run Code Online (Sandbox Code Playgroud) 我一直在尝试向FormRequest我的删除方法添加规则和消息,但请求将返回空白,并且规则每次都失败.
是否可以在删除方法中获取请求数据?
这是我的请求类:
use App\Http\Requests\Request;
class DeleteRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'staff_id' => ['required', 'exists:users,uid'],
'reason' => ['required', 'string'],
];
}
/**
* Get custom messages for validator errors.
*
* @return array …Run Code Online (Sandbox Code Playgroud) 如何在删除请求中通过httpClient传递body?
请检查我的代码。有什么想法可以在删除请求中通过正文传递数据吗?没有正确的来源如何在 Angular 5 中调用此请求。
let body = removeFile;
return this.httpClient.delete(`${apiRoot}RemoveQueryData`, {
headers: new HttpHeaders().set('Content-Type', 'application/json').set('Authorization', `Bearer ${accessToken}`),
observe: removeFile
})
Run Code Online (Sandbox Code Playgroud)
我正在观察那个身体。它抛出以下错误。
错误:
Error: Unreachable: unhandled observe type [object Object]}
at HttpClient.request (http.js:1520)
at HttpClient.delete (http.js:1546)
Run Code Online (Sandbox Code Playgroud) 我正在为我的 Django Rest Framework API 编写测试。
我一直在测试“删除”。
我对“创建”的测试工作正常。
这是我的测试代码:
import json
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from users.models import CustomUser
from lists.models import List, Item
class ListAPITest(APITestCase):
@classmethod
def setUp(self):
self.data = {'name': 'Test list', 'description':'A description', 'item': [
{'name': 'Item 1 Name', 'description': 'Item 1 description', 'order': 1},
{'name': 'Item 2 Name', 'description': 'Item 2 description', 'order': 2},
{'name': 'Item 3 Name', 'description': 'Item 3 description', 'order': 3},
{'name': 'Item 4 Name', …Run Code Online (Sandbox Code Playgroud) http-delete ×10
http ×4
httpclient ×2
python ×2
angular ×1
angular5 ×1
angularjs ×1
api ×1
body-parser ×1
c# ×1
express ×1
java ×1
json ×1
laravel ×1
laravel-5 ×1
node.js ×1
php ×1
rest ×1
sharepoint ×1
spring ×1
spring-mvc ×1
testing ×1