我正在尝试向servlet发送POST请求.请求以这种方式通过jQuery发送:
var productCategory = new Object();
productCategory.idProductCategory = 1;
productCategory.description = "Descrizione2";
newCategory(productCategory);
Run Code Online (Sandbox Code Playgroud)
newCategory在哪里
function newCategory(productCategory)
{
$.postJSON("ajax/newproductcategory", productCategory, function(
idProductCategory)
{
console.debug("Inserted: " + idProductCategory);
});
}
Run Code Online (Sandbox Code Playgroud)
和postJSON是
$.postJSON = function(url, data, callback) {
return jQuery.ajax({
'type': 'POST',
'url': url,
'contentType': 'application/json',
'data': JSON.stringify(data),
'dataType': 'json',
'success': callback
});
};
Run Code Online (Sandbox Code Playgroud)
使用firebug,我看到JSON正确发送:
{"idProductCategory":1,"description":"Descrizione2"}
Run Code Online (Sandbox Code Playgroud)
但我得到415不支持的媒体类型.Spring mvc控制器有签名
@RequestMapping(value = "/ajax/newproductcategory", method = RequestMethod.POST)
public @ResponseBody
Integer newProductCategory(HttpServletRequest request,
@RequestBody ProductCategory productCategory)
Run Code Online (Sandbox Code Playgroud)
几天前它工作,现在不是.如果需要,我会显示更多代码.谢谢
我正在使用JSON请求调用REST服务,它给出了Http 415"不支持的媒体类型"错误.
请求内容类型设置为("Content-Type","application/json; charset = utf8").
如果我在请求中不包含Json对象,它可以正常工作.我正在为json使用google-gson-2.2.4库.
我尝试使用几个不同的库,但它没有任何区别.
有人可以帮我解决这个问题吗?
这是我的代码:
public static void main(String[] args) throws Exception
{
JsonObject requestJson = new JsonObject();
String url = "xxx";
//method call for generating json
requestJson = generateJSON();
URL myurl = new URL(url);
HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=utf8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Method", "POST");
OutputStream os = con.getOutputStream();
os.write(requestJson.toString().getBytes("UTF-8"));
os.close();
StringBuilder sb = new StringBuilder();
int HttpResult =con.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"utf-8"));
String line = null;
while …
Run Code Online (Sandbox Code Playgroud) 我有一个现有的Web API 2服务,需要修改其中一个方法以将自定义对象作为另一个参数,目前该方法有一个参数,它是来自URL的简单字符串.将自定义对象添加为参数后,从.NET Windows应用程序调用服务时,我现在收到415不支持的媒体类型错误.有趣的是,我可以使用javascript和jquery ajax方法成功调用此方法.
Web API 2服务方法如下所示:
<HttpPost>
<HttpGet>
<Route("{view}")>
Public Function GetResultsWithView(view As String, pPaging As Paging) As HttpResponseMessage
Dim resp As New HttpResponseMessage
Dim lstrFetchXml As String = String.Empty
Dim lstrResults As String = String.Empty
Try
'... do some work here to generate xml string for the response
'// write xml results to response
resp.Content = New StringContent(lstrResults)
resp.Content.Headers.ContentType.MediaType = "text/xml"
resp.Headers.Add("Status-Message", "Query executed successfully")
resp.StatusCode = HttpStatusCode.OK
Catch ex As Exception
resp.StatusCode = HttpStatusCode.InternalServerError
resp.Headers.Add("Status-Message", String.Format("Error …
Run Code Online (Sandbox Code Playgroud) vb.net json asp.net-web-api http-status-code-415 asp.net-web-api2
我正在尝试使用WebApi PUT方法更新数据.我的代码之前工作正常,但突然间我开始得到这个错误.
"Message":"The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'xEmployee' from content with media type 'application/octet-stream'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException".
Run Code Online (Sandbox Code Playgroud)
这是标题:响应标题.
HTTP/1.1 415 Unsupported Media Type
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
Set-Cookie: Role=D65520F37D105E39C1A92C15CD482E378F32A769592AC7D8305285A5B9B90362F7F2F13F14E6DC220E44D26940B06B52E7460EF13184F245805AF9523D1072464F4BD06AFB4F8AEB8B7D8BF607A8922C6041A3A4C636BF3B26388E606A94FE43; expires=Tue, 07-Oct-2014 09:49:56 GMT; path=/
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 07 Oct 2014 09:19:56 GMT
Content-Length: 809
Run Code Online (Sandbox Code Playgroud)
请求标题:
PUT /api/xemployees/2110481232 HTTP/1.1 …
Run Code Online (Sandbox Code Playgroud) 我正在研究Java restful web服务.在测试restful服务时,我得到的响应对于GET和DELETE方法是正确的,但它不适用于POST和PUT方法.谁能帮我?我写了以下代码:
StudentService.java
@Stateless
@Path("students")
public class StudentService extends StudentServiceLocal<Students> {
@PersistenceContext(unitName = "RestFulAPIPU")
private EntityManager em;
public StudentsFacadeREST() {
super(Students.class);
}
@POST
@Override
@Consumes({"application/xml", "application/json"})
public String create(Students entity) {
return(super.create(entity));
}
@PUT
@Override
@Consumes({"application/xml", "application/json"})
public String edit(@PathParam("id") Students entity) {
return(super.edit(entity));
}
@DELETE
@Path("{id}")
public String remove(@PathParam("id") Integer id) {
return(super.remove(super.find(id)));
}
@GET
@Path("{id}")
@Produces({"application/xml", "application/json"})
public Students find(@PathParam("id") Integer id) {
return super.find(id);
}
@GET
@Override
@Produces({"application/xml", "application/json"})
public List<Students> findAll() {
return super.findAll();
} …
Run Code Online (Sandbox Code Playgroud) 将数据发布到服务器时出现 415 错误。这是我的代码如何解决这个问题。提前致谢!
import requests
import json
from requests.auth import HTTPBasicAuth
#headers = {'content-type':'application/javascript'}
#headers={'content-type':'application/json', 'Accept':'application/json'}
url = 'http://IPadress/kaaAdmin/rest/api/sendNotification'
data = {"name": "Value"}
r = requests.post(url, auth=HTTPBasicAuth('shany.ka', 'shanky1213'),json=data)
print(r.status_code)
Run Code Online (Sandbox Code Playgroud) 嗨,我正在尝试将json数据发布到使用Jersey实现的Restful WS.我通过jquery-ajax发布数据.为什么我要使用HTTP Status-415不支持的媒体类型?谢谢.
点击此处查看firebug描述的屏幕截图
//post method handler
@Path("/newentry")
public class NewEntry {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response newEntry(String data) {
//doStuff
}
}
// ajax call
$.ajax({
url: "http://localhost:8080/FirstRestWebService/rest/newentry",
type: "post",
data: formToJSON(),
dataType : "json",
success: function(data){
alert("success");
},
error:function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
function formToJSON() {
return JSON.stringify({
"name": $("input#emp_name").val(),
...
"username": $('input#username').val(),
"password": $('input#password').val()
});
Run Code Online (Sandbox Code Playgroud)
单击此处查看firebug说明的屏幕截图 我能够通过Jersey Client成功测试WS.上面的AJAX调用有什么问题?谢谢.
我是REST和AngularJS的新手,但是经过几个小时的搜寻后,我找不到我的问题的任何答案:
我正在尝试从我的angularjs前端向我在Java中实现的后端(使用JPA)执行POST请求。
当我尝试创建json-object并执行POST时,我总是收到415(不支持的媒体类型)错误。
(实际上,我什至没有“进入”该服务的范围(即“ IN SERVICE”没有被打印到控制台)。如果我添加postData.toJSON(),它实际上会被“ POSTED”,但是到达null ...
如何成功格式化“ postData”以便成功发布?
(我也试图写Date属性而不带'“'-没运气...)
谢谢您的帮助!
前端:
app.controller('WorkController',function($ scope,$ http){
$scope.saveWork = function () {
var postData = {
"status" : "OPEN",
"startDate": "1338364250000",
"endDate": "1336364253400",
"WorkText" : "Test"
};
$http.post("http://localhost:8080/service/v1/saveWork", postData)
.success(function(data, status, headers, config){
console.log("IN SAVE WORK - SUCCESS");
console.log(status);
})
.error(function(){
console.log("ERROR IN SAVE WORK!");
})
}
Run Code Online (Sandbox Code Playgroud)
});
服务:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response save(WorkDto wo){
System.out.println("IN SERVICE");
if(ass == null){
System.out.println("Could nor persist work- null");
return Response.noContent().build();
} else{ …
Run Code Online (Sandbox Code Playgroud) 我们有一个 .netcore 3.1 ApiController,其端点侦听 PATCH 请求,并定义了一个用于集成/API 测试的测试服务器。
使用 Postman 发送的 PATCH 请求工作得很好,但在 XUnit 测试中通过 HttpClient 发送的请求失败,并显示 415 不支持的媒体类型。
邮递员补丁请求:除了承载令牌和内容类型之外没有特定标头:“application/json”
在测试中,我们使用 WebApplicationFactory 及其 HttpClient 的factory.CreateClient()。
这不应该是 Json 序列化的问题,因为我通过调试器查看了内容,它似乎序列化得很好。
此外,我们的 POST 方法完全开箱即用,使用完全相同的代码(将“PATCH”替换为“POST”等)
期待一些建议。另外,如果您需要更多信息,请告诉我。多谢。
控制器:
[HttpPatch("{id}")]
public async Task<ActionResult<Unit>> Edit(Edit.Command request)
{
return await Mediator.Send(request);
}
Run Code Online (Sandbox Code Playgroud)
命令:
public class Command : IRequest
{
public string Id { get; set; }
public JsonPatchDocument<ObjectDTO> PatchDocument { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
测试:
[InlineData(/* inline data goes here */)]
public async void TestEdit_Ok(/* required parameters for the …
Run Code Online (Sandbox Code Playgroud) 我正在做一个Spring MVC控制器,我仍然遇到POST操作问题.我已经在stackoverflow上阅读了许多解决方案而无法解决我的问题.
我目前的成就:
POST
用JSON正文发送请求,return = 415 UNSUPPORTED_MEDIA_TYPE
1)我在我的pom.xml中添加了Jackson API:1.8.5
2)我的Spring配置文件:我添加了所有必要的部分:
3)我的模型对象很简单:具有Id,Name和金额的账户
@Document
public class Account implements Serializable {
private static final long serialVersionUID = 9058933587701674803L;
@Id
private String id;
private String name;
private Double amount=0.0;
// and all get and set methods
Run Code Online (Sandbox Code Playgroud)
4)最后我简化的Controller类:
@Controller
public class AdminController {
@RequestMapping(value="/account", method=RequestMethod.POST,
headers = {"content-type=application/json"})
@ResponseStatus( HttpStatus.CREATED )
public void addAccount(@RequestBody Account account){
log.debug("account from json request " + account);
}
@RequestMapping(value="/account/{accountId}", method=RequestMethod.GET) …
Run Code Online (Sandbox Code Playgroud) 我是Spring Boot的初学者,正在学习自己的方法。
在使用Spring Boot的REST Web服务中进行POST请求期间,如何解决“ HTTP-415”错误,如下所示?我已经尝试过@RequestMapping
注解@RequestParam
。@RequestParam
给出其他错误401。但是,415与@RequestMapping
和一致@PostMapping
。
与发出@PostMapping
请求。
{
"timestamp": "2018-12-31T18:29:36.727+0000",
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'text/plain;charset=UTF-8' not supported",
"trace": "org.springframework.web.HttpMediaTypeNotSupportedException: Content type
'text/plain;charset=UTF-8' not supported\r\n\tat
org.springframework.web.servlet.mvc.method.annotation.
AbstractMessageConverterMethodArgumentResolver.
readWithMessageConverters
(AbstractMessageConverterMethodArgumentResolver.java:224)\r\n\tat
org.springframework.web.servlet.mvc.method.annotation.
RequestResponseBodyMethodProcessor.
readWithMessageConverters(RequestResponseBodyMethodProcessor.java:157)
\r\n\tat org.springframework.web.servlet.mvc.method.
annotation.RequestResponseBodyMethodProcessor.
resolveArgument(RequestResponseBodyMethodProcessor.java:130)
\r\n\tat...................
Run Code Online (Sandbox Code Playgroud)
在提出以下要求时:
StudentController.java
@RestController
public class StudentController {
@Autowired
private StudentService studentService;
:
:
@PostMapping("/students/{studentId}/courses")
public ResponseEntity<Void> registerStudentForCourse(
@PathVariable String studentId,
@RequestBody Course newCourse) {
Course course = …
Run Code Online (Sandbox Code Playgroud) 首先,这是一个有效的 POST 映射:
app.MapPost("formulary/uploadSingle/{oldSys}/{newSys}",
async (HttpRequest request, string oldSys, string newSys) =>
{
return await MapUploadSingleFileEndpoint(request, oldSys, newSys);
}).Accepts<IFormFile>("form-data")
.Produces(StatusCodes.Status200OK)
.Produces(StatusCodes.Status400BadRequest);
Run Code Online (Sandbox Code Playgroud)
MapUploadSingleFileEndpoint 方法使用整个主体来获取文件,如下所示:
using var reader = new StreamReader(request.Body, Encoding.UTF8);
Run Code Online (Sandbox Code Playgroud)
这在 Swagger UI 中完美运行,它显示 2 个参数以及一个文件选择对话框,点击执行返回 200。然后我可以在服务器本地复制文件并随意操作它。请注意,将表单数据更改为任何其他内容都会导致 Swagger 不显示文件部分对话框。
这就是问题所在。我需要一个采用相同参数的端点,只是它需要 2 个文件才能工作。因为我正在阅读整个正文以在前面的方法中获取单个文件,所以我显然不能在这里做同样的事情。即使情况并非如此,IFormFile 类型也会生成一个仅允许单个选择的文件选择器对话框。我尝试将接受更改为IFormFileCollection
或,List<IFormFile>
但这不起作用,Swagger UI 上没有文件选择器。我决定尝试创建这个自定义请求模型:
public class MultipleFormularyFilesRequest
{
public string OldExternalSystemName { get; set; }
public string NewExternalSystemName { get; set; }
public IFormFile FirstFile { get; set; }
public IFormFile SecondFile { get; set; …
Run Code Online (Sandbox Code Playgroud) 即使知道这个错误,我也无法解决我的问题!
重置服务在此代码中声明:
@POST
@Transactional
@Consumes(MediaType.APPLICATION_JSON)
@Path("/addProduct")
public void addProductToShoppingBag(JSONObject object) throws JSONException
Run Code Online (Sandbox Code Playgroud)
我正在使用此javascript发送POST请求:
$.ajax({
header: 'application/json',
type: 'POST',
data: $.toJSON({
member_id: "1",
products_id: ["0","1"]
}),
url: url
}).done(success).error(failure);
Run Code Online (Sandbox Code Playgroud)
而且我得到了415 - 不支持的媒体类型错误!任何的想法 ?
java ×3
json ×3
post ×3
ajax ×2
c# ×2
jersey ×2
rest ×2
spring-mvc ×2
web-services ×2
.net-6.0 ×1
angularjs ×1
asp.net-core ×1
javascript ×1
jpa ×1
jquery ×1
json-patch ×1
minimal-apis ×1
patch ×1
python ×1
spring ×1
spring-boot ×1
vb.net ×1