java - 客户端请求的 RestEasy Http header

标签 java rest jboss resteasy rest-client

我正在使用 RestEasy ClientTRequest API 访问 Rest Web 服务。如何为客户端请求设置http header 。

我需要添加以下名称值对作为 http header 。

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




    }

提前致谢

尝试过这个coxe。但不工作

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

您可以找到带有解释的好例子here .

关于java - 客户端请求的 RestEasy Http header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26094536/

相关文章:

java - 崩溃后停止线程/线程调用自身中断?

java - 在 Java 中使用数据库结果动态构建 JSON

design-patterns - REST 是否适用于大型 3NF 模型

java - 无法使用@Value注释从Spring Boot中的属性文件中读取值

rest - 带有 Netbeans 的 Tomcat restful Web 服务数据库 (JPA) 无法工作

jboss - 为 JBoss EAP 6.3 (HornetQ 2.3.x) 配置 JmsToolBox

java - 为什么我需要将随机修改器更改为静态?

java - 以编程方式验证并签署 Jar

java - 帮助我使用 Stateful beans

windows - 将 JBoss 7.1.1.Final 作为 Windows 服务运行