Java 如何在发布请求时在HTTP标头中设置自定义变量

Java 如何在发布请求时在HTTP标头中设置自定义变量,java,httpwebrequest,http-headers,Java,Httpwebrequest,Http Headers,我想将我的机器名作为自定义名称添加到http请求头中 JAVA中的变量 这是我的密码: private void sendIssuesToWebService(问题){ //TODO自动生成的方法存根 System.out.println(“\n\n”); //LOG.info(“发送问题:+issue.getKey()); HttpURLConnection ycSend=null; BufferedReader in1=null; JSONObject j=null; 试一试{ URL ur

我想将我的机器名作为自定义名称添加到http请求头中 JAVA中的变量

这是我的密码:

private void sendIssuesToWebService(问题){
//TODO自动生成的方法存根
System.out.println(“\n\n”);
//LOG.info(“发送问题:+issue.getKey());
HttpURLConnection ycSend=null;
BufferedReader in1=null;
JSONObject j=null;
试一试{
URL urlSend=null;
试一试{
urlSend=新URL(targetURL+“发布/导入组织”);
}
捕获(格式错误){
//TODO自动生成的捕捉块
严重(“验证时URL格式错误的异常”);
e、 printStackTrace();
}
试一试{
ycSend=(HttpURLConnection)urlSend.openConnection();
}
捕获(IOE异常){
//TODO自动生成的捕捉块
严重(“身份验证时Http URL连接出错”);
e、 printStackTrace();
}
ycSend.setDoOutput(真);
ycSend.setRequestMethod(“POST”);
setRequestProperty(“内容类型”、“应用程序/json”);
试一试{
OutputStreamWriter outSend=null;
outSend=新的OutputStreamWriter(ycSend.getOutputStream());
outSend.write(发布历史JSONSTR);
outSend.flush();
}捕获(例外e)
{
LOG.severe(“发送问题时无法写入输出流”);
}
System.out.println(ycSend.getResponseCode()+“\n\n\n”);
如果(ycSend.getResponseCode()!=200){
in1=新的BufferedReader(新的InputStreamReader(
ycSend.getErrorStream());
字符串输入线;
而((inputLine=in1.readLine())!=null)
inputResponse=inputResponse+inputLine;
//System.out.println(“$$$$$$”+输入响应);
试一试{
j=新的JSONObject(输入响应);
LOG.info(j.get(“errors”).toString();
}
捕获(例外e){
String errorTitle=inputResponse.substring(inputResponse.indexOf(“”+7,inputResponse.indexOf(“”));
严重日志(错误标题);
}
LOG.severe(“向web服务发送问题时出错,问题密钥为“+Issue.getKey()”);
//LOG.severy(“错误为:”+j.get(“错误”));
}
其他的
{
LOG.info(“Issue”+Issue.getKey()+“发送成功”);
countIssues++;
System.out.println(“\n\n”);
}
//LOG.info(“Issue******”+Issue.getKey()+”随响应一起发送:“+inputResponse”);
}
捕获(例外e)
{
LOG.severe(“向web服务发送问题时出错,问题密钥为“+Issue.getKey()”);
//LOG.severy(yc.getResponseMessage());
//LOG.severy(“错误为:”+j.get(“错误”));
e、 printStackTrace();
}
}

我相信您只想添加另一个类似于content type的requestProperty

ycSend.setRequestProperty("Machine-Name", MachineName);
也许会有帮助。或者,您可以通过Apache来实现这一点

要获取主机名,可以执行以下操作:

try {
    InetAddress addr = InetAddress.getLocalHost();

    // Get hostname
    String hostname = addr.getHostName();
} catch (UnknownHostException e) {
  //DO SOMETHING 
}
try {
    InetAddress addr = InetAddress.getLocalHost();

    // Get hostname
    String hostname = addr.getHostName();
} catch (UnknownHostException e) {
  //DO SOMETHING 
}