2014-09-29 182 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