繁体   English   中英

客户端请求的ReastEasy Http标头

[英]ReastEasy Http Header for Client Request

我正在使用RestEasy ClienTRequest API访问Rest Web服务。 如何为客户端请求设置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);

只需使用一个简单的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();

您可以在此处找到带有说明的良好示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM