Getting (415) Unsupported Media Type error

What I have to do is that I have to post JSON data in given URL Where my JSON looks like

{
    "trip_title":"My Hotel Booking",
    "traveler_info":{
        "first_name":"Edward",
        "middle_name":"",
        "last_name":"Cullen",
        "phone":{
            "country_code":"1",
            "area_code":"425",
            "number":"6795089"
        },
        "email":"[email protected]"
    },
    "billing_info":{
        "credit_card":{
            "card_number":"47135821",
            "card_type":"Visa",
            "card_security_code":"123",
            "expiration_month":"09",
            "expiration_year":"2017"
        },
        "first_name":"Edward",
        "last_name":"Cullen",
        "billing_address":{
            "street1":"Expedia Inc",
            "street2":"108th Ave NE",
            "suite":"333",
            "city":"Bellevue",
            "state":"WA",
            "country":"USA",
            "zipcode":"98004"
        },
        "phone":{
            "country_code":"1",
            "area_code":"425",
            "number":"782"
        }
    },
    "marketing_code":""
}

And my function

string message = "URL";
_body="JSON DATA";
HttpWebRequest request = HttpWebRequest.Create(message) as HttpWebRequest;
if (!string.IsNullOrEmpty(_body))
{
    request.ContentType =  "text/json";
    request.Method =  "POST";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(_body);
        streamWriter.Flush();
        streamWriter.Close();
    }
}

using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
{
    using (StreamReader reader = new StreamReader(webresponse.GetResponseStream()))
    {
        string response = reader.ReadToEnd();
    }
}

And when I am posting it; I am getting an error

"The remote server returned an error: (415) Unsupported Media Type."

Anybody have idea about it; where I am mistaking?

Score: 20
Tags: c#, json, http, post, httpwebrequest
Views: 69772
Date posted: 10/30/2012

Specify supported media types when sending "415 unsupported media type"

If a clients sends data in an unsupported media type to a HTTP server, the server answers with status "415 unsupported media type". But how to tell the client what media types are supported? Is there a standard or at least a recommended way to do so? Or would it just be written to the response body as text?

Score: 13
Tags: http, rest, http-status-codes, httpresponse, content-negotiation
Views: 11732
Date posted: 7/27/2010

HTTP Status 415 - Unsupported Media Type

I am working on Java restful web service. While testing the restful service I am getting the responses correct for GET and DELETE methods but it is not working for POST and PUT methods. Can anyone help me? I have written the following code:

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();
    }

    @GET
    @Path("{from}/{to}")
    @Produces({"application/xml", "application/json"})
    public List<Students> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
        return super.findRange(new int[]{from, to});
    }

    @GET
    @Path("count")
    @Produces("text/plain")
    public String countREST() {
        return String.valueOf(super.count());
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

}

StudentServiceLocal.java

public abstract class AbstractFacade<T> {
    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public String create(T entity) {
        getEntityManager().persist(entity);
        return "inserted";
    }

    public String edit(T entity) {
           getEntityManager().merge(entity);
        return "Updated";
    }

    public String remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));        
            return "deleted";  
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        javax.persistence.Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}

Students.java

@Entity
@Table(name = "students")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Students.findAll", query = "SELECT s FROM Students s"),
    @NamedQuery(name = "Students.findByRollno", query = "SELECT s FROM Students s WHERE s.rollno = :rollno"),
    @NamedQuery(name = "Students.findByName", query = "SELECT s FROM Students s WHERE s.name = :name")})
public class Students implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Column(name = "rollno")
    private Integer rollno;
    @Size(max = 20)
    @Column(name = "name")
    private String name;

    public Students() {
    }

    public Students(Integer rollno) {
        this.rollno = rollno;
    }

    public Integer getRollno() {
        return rollno;
    }

    public void setRollno(Integer rollno) {
        this.rollno = rollno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (rollno != null ? rollno.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Students)) {
            return false;
        }
        Students other = (Students) object;
        if ((this.rollno == null && other.rollno != null) || (this.rollno != null && !this.rollno.equals(other.rollno))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.ikanksha.rest.entity.Students[ rollno=" + rollno + " ]";
    }

}
Score: 11
Tags: java, web-services, rest, http-status-code-415
Views: 62761
Date posted: 2/7/2013

Jersey 415 Unsupported Media Type

I have been trying since hours to correct http error 415 Unsupported Media Type but it is still showing media unsupported page. I am adding headers application/json in Postman.

Here is my Java Code

package lostLove;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;  
import javax.ws.rs.POST;
import javax.ws.rs.Path;  
import javax.ws.rs.PathParam;  
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; 

import org.json.JSONObject;


@Path("/Story") 
public class Story {

      @POST
      @Consumes({"application/json"})
      @Produces(MediaType.APPLICATION_JSON)
    //  @Consumes(MediaType.APPLICATION_JSON)
    //  @Path("/Story") 
      public JSONObject sayJsonTextHello(JSONObject inputJsonObj) throws Exception {

        String input = (String) inputJsonObj.get("input");
        String output = "The input you sent is :" + input;
        JSONObject outputJsonObj = new JSONObject();
        outputJsonObj.put("output", output);

        return outputJsonObj;
      }

      @GET  
      @Produces(MediaType.TEXT_PLAIN)  

      public String sayPlainTextHello() {  
        return "hello";
      }

}

here is my web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>LostLove</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 <servlet>  
    <servlet-name>Jersey REST Service</servlet-name>  
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>  
    <init-param>  
        <param-name>jersey.config.server.provider.packages</param-name>  
        <param-value>lostLove</param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
  </servlet>  
  <servlet-mapping>  
    <servlet-name>Jersey REST Service</servlet-name>  
    <url-pattern>/rest/*</url-pattern>  
  </servlet-mapping>
</web-app>
Score: 6
Tags: java, json, rest, jersey, jax-rs
Views: 14637
Date posted: 6/7/2015

How to Override 415 response in ASP.Net Core2.2

in .net core 2.2 ,has a default json with statuscode 415 like

{
   "type":"https://tools.ietf.org/html/rfc7231#section-6.5.13",
   "title":"Unsupported Media Type",
   "status":415,
   "traceId":"8000003e-0001-f500-b63f-84710c7967bb"
}

I don't know how this JSON came from. I follow the example below to rewrite json

But I got a different result,It added a section to the original json . This is my Wireshark Result

HTTP/1.1 415 Unsupported Media Type Transfer-Encoding: chunked

Content-Type: application/problem+json; charset=utf-8 Server:

Microsoft-IIS/10.0 X-Powered-By: ASP.NET Date: Mon, 06 May 2019 09:03:56 GMT

{
   "type":"https://tools.ietf.org/html/rfc7231#section-6.5.13",
   "title":"Unsupported Media Type",
   "status":415,
   "traceId":"8000002c-0002-fb00-b63f-84710c7967bb"
}
{
   "data":"this is custom message"
}

Filter:

public class MediaTypeResouceFilter : Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
        if (context.HttpContext.Response.StatusCode == 415)
        {
            var jsonString = JsonConvert.SerializeObject(new { data = "this is custom message" });
            byte[] data = Encoding.UTF8.GetBytes(jsonString);
            context.HttpContext.Response.Body.WriteAsync(data, 0, data.Length);
        }
    }
}
Score: 5
Tags: c#, asp.net-core
Views: 1427
Date posted: 5/6/2019


1


© 2021 Search Overflow
Contributions licensed under cc by-sa