title: How to POST an authenticated Jenkins job using Java
body: <p>All:</p>
  
  <p>I need to be able to POST a job to Jenkins using the Jenkins REST API but have not been able to get past authentication. I have been attempting to do this for a few days now and have researched answers on both this site and on the Jenkins site. I have been trying to use the Apache HttpClient with no success (even with preemptive validation). I keep getting error code 403 - forbidden. Has anyone been able to do this successfully? Here is the code that I am working with:</p>
  
  <pre><code>package stackoverflow.question;
  
  import gsafame.sample;
  
  import java.io.IOException;
  import java.util.ArrayList;
  import java.util.List;
  import java.util.logging.Logger;
  
  import org.apache.http.HttpEntity;
  import org.apache.http.HttpHost;
  import org.apache.http.NameValuePair;
  import org.apache.http.auth.AuthScope;
  import org.apache.http.auth.UsernamePasswordCredentials;
  import org.apache.http.client.AuthCache;
  import org.apache.http.client.ClientProtocolException;
  import org.apache.http.client.CredentialsProvider;
  import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.CloseableHttpResponse;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.client.protocol.HttpClientContext;
  import org.apache.http.impl.auth.BasicScheme;
  import org.apache.http.impl.client.BasicAuthCache;
  import org.apache.http.impl.client.BasicCredentialsProvider;
  import org.apache.http.impl.client.CloseableHttpClient;
  import org.apache.http.impl.client.HttpClients;
  import org.apache.http.message.BasicNameValuePair;
  import org.apache.http.util.EntityUtils;
  
  public class PreEmptiveAuth {
  final Logger log = Logger.getLogger(sample.class.getCanonicalName());
  private JobData jd;
  private CredentialsProvider credpro;
  private AuthScope as;
  private UsernamePasswordCredentials upc;
  private String url;
  
  public PreEmptiveAuth(JobData jd) {
      this.jd = jd;
      credpro = new BasicCredentialsProvider();
      as = new AuthScope(jd.getServer(), 443);
      upc = new UsernamePasswordCredentials(jd.getUsername(), jd.getPassword());
      credpro.setCredentials(as, upc);
      url = String.format("%s:8080/jenkins/job/%s/buildWithParameters", jd.getServer(), jd.getJob());
  }
  
  public void runTagJob() throws ClientProtocolException, IOException {
      log.entering(this.getClass().getCanonicalName(), "runTagJob");
      log.info("Entering runTagJob");
      CloseableHttpClient httpclient = HttpClients.custom()
              .setDefaultCredentialsProvider(credpro).build();
      HttpPost httpPost = new HttpPost(url);
      List &lt;NameValuePair&gt; nvps = new ArrayList &lt;NameValuePair&gt;();
      nvps.add(new BasicNameValuePair("username", jd.getUsername()));
      nvps.add(new BasicNameValuePair("password", jd.getPassword()));
      nvps.add(new BasicNameValuePair("apiToken", jd.getToken()));
      httpPost.setEntity(new UrlEncodedFormEntity(nvps));
      CloseableHttpResponse response2 = httpclient.execute(httpPost);
  
      try {
          System.out.println(response2.getStatusLine());
          HttpEntity entity2 = response2.getEntity();
          // do something useful with the response body
          // and ensure it is fully consumed
          EntityUtils.consume(entity2);
      } finally {
          response2.close();
      }
      log.info("Exiting runTagJob");
      log.exiting(this.getClass().getCanonicalName(), "runTagJob");
  }
  
  public void runPreTagJob() throws ClientProtocolException, IOException {
      log.entering(this.getClass().getCanonicalName(), "runPreTagJob");
      log.info("Entering runPreTagJob");
      HttpHost targetHost = new HttpHost(jd.getServer(), 8080, "http");
      CloseableHttpClient httpclient = HttpClients.custom()
              .setDefaultCredentialsProvider(credpro).build();
      try {
  
          // Create AuthCache instance
          AuthCache authCache = new BasicAuthCache();
          // Generate BASIC scheme object and add it to the local auth cache
          BasicScheme basicAuth = new BasicScheme();
          authCache.put(targetHost, basicAuth);
  
          // Add AuthCache to the execution context
          HttpClientContext localContext = HttpClientContext.create();
          localContext.setAuthCache(authCache);
  
          HttpPost httpPost = new HttpPost(url);
          List &lt;NameValuePair&gt; nvps = new ArrayList &lt;NameValuePair&gt;();
          nvps.add(new BasicNameValuePair("username", jd.getUsername()));
          nvps.add(new BasicNameValuePair("password", jd.getPassword()));
          nvps.add(new BasicNameValuePair("apiToken", jd.getToken()));
          httpPost.setEntity(new UrlEncodedFormEntity(nvps));
          CloseableHttpResponse response2 = httpclient.execute(targetHost, httpPost, localContext);
  
          try {
              System.out.println(response2.getStatusLine());
              HttpEntity entity2 = response2.getEntity();
              // do something useful with the response body
              // and ensure it is fully consumed
              EntityUtils.consume(entity2);
          } finally {
              response2.close();
          }    
      } finally {
          httpclient.close();
      }
      log.info("Exiting runPreTagJob");
      log.exiting(this.getClass().getCanonicalName(), "runPreTagJob");
  }
  
  }
  </code></pre>
  
  <p>The JobData object that gets passed into this class contains information like username, password, server, and job information. I hope this helps!</p>