2017-05-09 550 views
0

我需要發佈一個Json到服務器並獲取Json結果,我使用restTemplate實現。但問題是它總是發出一個錯誤java.net.UnknownHostException。 控制器:使用restTemplate的post方法,錯誤java.net.UnknownHostException

@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> 

服務: 我CONFIG在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); 

任何我失蹤??。它適用於郵遞員。我在公司工作,所以我必須配置標題的主機和端口。

錯誤:

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).... 
+0

你得到的答案是一樣的嗎? –

回答

0

可能是貴公司的代理。你可以在你的彈簧配置中定義它:

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