我正在使用 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/