1
votes

I need to post a Json to a server and get the Json result , which i'm using restTemplate to implement. But the problem is it always making an error

java.net.UnknownHostException

Controller :

@RequestMapping(value = "/test")
public String test(HttpServletRequest request, HttpServletResponse response){
    String user=request.getParameter("txtUser");
    HttpSession session = request.getSession();
    session.setAttribute("result",accountService.findFarmsByUser(user));
    return "test";
}

test.jsp :

<form action="test">
    <input type="text" value="insert search" name="txtUser">
    <input type="submit" value="submit" name="btnSubmit">
    <input type="text" value="" name="result">
</form>

Service:

I'm config the port and host in xml.

  //create  request json
    JSONObject json = new JSONObject().put(
            "input",
            new JSONObject().put(
                    "username",
                    "Administrator"));

    // set headers
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(json.toString(), headers);
    headers.set(proxyHost,Host);
    headers.set(proxyPort,Port);

    ResponseEntity<String> loginResponse = restTemplate
            .exchange(url, HttpMethod.POST, entity, String.class);
    logger.info("reutrn data: {}",loginResponse);

Anything I'm missing ??. It works fine with postman.I'm working in company so I have to config the host and port for header.

Error:

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://{myserver:port}/Thingworx/Things/{...}/Services/findUser": {myserver}; nested exception is java.net.UnknownHostException: {myserver} at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:607) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557) at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475) at spring.web.services.impl.AccountSerivceImpl.findUser(AccountSerivceImpl.java:115) at spring.web.controller.PageController.test(PageController.java:89) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)....

1
did you get answer to the same?manocha_ak

1 Answers

1
votes

Might be a proxy in your company. You can define it in your spring config:

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("clientproxy.corp.url", 8080));
        requestFactory.setProxy(proxy);
        return builder.requestFactory(requestFactory).setConnectTimeout(5000).setReadTimeout(5000).build();
    }