2014-09-29 186 views
1

我正在使用RestEasy ClienTRequest API访问其他Web服务。如何为客户端请求设置http标头。客户端请求的ReastEasy Http标头

我需要将以下名称值对添加为http标头。

username raj 
password raj 

这是客户端代码提前

试过这种考克斯

public void getResponse(String uri, Defect defect) { 

     StringWriter writer = new StringWriter(); 
     try{ 
     JAXBContext jaxbContext = JAXBContext.newInstance(Defect.class); 
     Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); 
     jaxbMarshaller.marshal(defect, writer); 
     }catch(JAXBException e){ 

     } 

     //Define the API URI where API will be accessed 
     ClientRequest request = new ClientRequest("https://dev.in/rest/service/create"); 

     //Set the accept header to tell the accepted response format 
     request.body("application/xml", writer.getBuffer().toString()); 
     // request.header("raj", "raj"); 
     //Send the request 
     ClientResponse response; 
     try { 
      response = request.post(); 
      int apiResponseCode = response.getResponseStatus().getStatusCode(); 
      if(response.getResponseStatus().getStatusCode() != 201) 
       { 
        throw new RuntimeException("Failed with HTTP error code : " + apiResponseCode); 
       } 
      System.out.println("response "+response.toString()); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     //First validate the api status code 




    } 

感谢。但不起作用

Map<String, String> headerParam = new HashMap<String, String>(); headerParam.put("username", "raj"); headerParam.put("password", "raj"); request.header(HttpHeaders.ACCEPT, headerParam); 
+0

Map headerParam = new HashMap (); \t headerParam.put(“username”,“raj”); \t headerParam.put(“password”,“raj”); \t \t request.header(HttpHeaders.ACCEPT,headerParam); – Rosh 2014-09-29 08:24:27

+1

ClientRequest已弃用。您可能需要使用[jaxrs-2.0客户端API](http://docs.jboss.org/resteasy/docs/3.0-beta-3/userguide/html/RESTEasy_Client_Framework.html),只需执行诸如“客户端。.TARGET(URL).request()接受(MediaType.APPLICATION_XML).header(...)头(...)得到(..);'。查看几个示例的['Invocation.Builder'](http://docs.oracle.com/javaee/7/api/javax/ws/rs/client/Invocation.Builder.html)类 – 2014-09-29 10:34:46

+0

@ peeskillet:你有没有任何示例代码? – Rosh 2014-09-29 10:47:38

回答

1

只需使用一个简单的http客户端。尝试下面的代码。确保你正确处理异常。

 URL url = new URL("https://dev.in/rest/service/create"); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setRequestMethod("POST"); 

     conn.setRequestProperty("Accept", "application/json;ver=1.0"); 
     conn.setRequestProperty("username", "raj"); 
     conn.setRequestProperty("password", "raj"); 

     String input = "{}" ; //set you json payload here.   
     OutputStream os = conn.getOutputStream(); 
     os.write(input.getBytes()); 

     os.flush();   
     conn.disconnect(); 

你可以找到很好的例子和解释here