Rosh
Rosh

Reputation: 1736

ReastEasy Http Header for Client Request

I'm accessing a rest web service using RestEasy ClienTRequest API. How can I set http header for the client request.

I need to add the following name value pair as http header.

username   raj
password   raj

This is the client code

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




    }

Thanks in advance

Tried this coxe. but not working

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

Upvotes: 1

Views: 1595

Answers (1)

Maleen Abewardana
Maleen Abewardana

Reputation: 14572

Just use a simple http client. Try following code. Make sure you handle exceptions properly.

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

You can find good examples with explanation here.

Upvotes: 1

Related Questions