我正在使用RestEasy ClienTRequest API访问其他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);
答案 0 :(得分: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找到很好的示例。