IT

JSON에서 HTTP 415 지원되지 않는 미디어 유형 오류

lottoking 2020. 8. 28. 19:38
반응형

JSON에서 HTTP 415 지원되지 않는 미디어 유형 오류


JSON 요청으로 REST 서비스를 호출하고 있는데 Http 415 "Unsupported Media Type"오류가 발생합니다.

요청 컨텐츠 유형은 ( "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 ((line = br.readLine()) != null) {  
        sb.append(line + "\n");  
        }
         br.close(); 
         System.out.println(""+sb.toString());  

    }else{
        System.out.println(con.getResponseCode());
        System.out.println(con.getResponseMessage());  
    }  

}
public static JsonObject generateJSON () throws MalformedURLException

{
   String s = "http://www.abc.com";
        s.replaceAll("/", "\\/");
    JsonObject reqparam=new JsonObject();
    reqparam.addProperty("type", "arl");
    reqparam.addProperty("action", "remove");
    reqparam.addProperty("domain", "staging");
    reqparam.addProperty("objects", s);
    return reqparam;

}
}

requestJson.toString의 값은 다음과 가변됩니다.

{ "type": "arl", "action": "remove", "domain": "staging", "objects": " http://www.abc.com "}


이유는 확실하지 않지만 줄 charset=utf8제거 con.setRequestProperty("Content-Type", "application/json; charset=utf8")하면 문제 해결됩니다.


콘텐츠 유형 추가 : application/json및 수락 :application/json


charset=utf8뒤에 공백이 없어야 하기 때문 application/json입니다. 잘 작동합니다. 그것을 사용하십시오application/json;charset=utf-8


jquery ajax 요청을하는 경우 추가하는 것을 잊지 마십시오.

contentType:'application/json'

HTTP 헤더 관리자를 추가하고 API의 헤더 이름과 값을 추가합니다. 예 : 콘텐츠 유형, 수락 등. 그러면 문제가 해결됩니다.


때때로 Charset Metada는 요청을 보내는 동안 json을 중단합니다. 요청 유형에 charset = utf8을 사용하지 않는 것이 좋습니다.


AJAX jQueryRequest 를 사용 하는 경우 반드시 신청해야합니다. 그렇지 않으면 415오류가 발생합니다.

dataType: "json",
contentType:'application/json'

"삭제"나머지 요청을 보냈는데 415로 실패했습니다. 내 서버가 API에 도달하는 데 사용하는 콘텐츠 유형을 확인했습니다. 제 경우에는 "application / json; charset = utf8"대신 "application / json"이었습니다.

그러니 API 개발자에게 물어보고 그동안 content-type = "application / json"으로 만 요청을 보내십시오.


나는 같은 문제가 있었다. 내 문제는 직렬화에 대한 복잡한 개체였습니다. 내 개체의 속성 중 하나는 Map<Object1, List<Object2>>. 내가 좋아하는이 속성을 변경할 List<Object3>경우 Object3포함 Object1Object2모든 것이 잘 작동합니다.


나는 이것이 그의 문제로 OP를 돕기에는 너무 늦다는 것을 알고 있지만,이 문제에 직면 한 우리 모두에게 json 데이터를 보유하기위한 클래스의 매개 변수로 생성자를 제거 하여이 문제를 해결했습니다.


구성에서 MappingJackson2HttpMessageConverter를 수동으로 추가하면 문제가 해결되었습니다.

@EnableWebMvc
@Configuration
@ComponentScan
public class RestConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        super.configureMessageConverters(messageConverters);
    }
}

그 이유는 디스패처 서블릿 xml 파일에 "주석 기반"을 추가하지 않았기 때문일 수 있습니다. 또한 헤더에 application / json으로 추가되지 않았기 때문일 수도 있습니다.


React RSAA 미들웨어 또는 이와 유사한 경우 헤더를 추가하십시오.

  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(model),

Request컨트롤러가받는 클래스를 업데이트하여이 문제를 해결했습니다 .

나는 제거 내에서 다음 클래스 수준 주석 Request내 서버 측에서 클래스를. 그 후 내 고객 은 415 오류를 얻지 못했습니다.

import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement

참고 URL : https://stackoverflow.com/questions/22566433/http-415-unsupported-media-type-error-with-json

반응형