HTTP Auth认证请求(附代理)-代码篇

2种方式

方式一:Http请求头上添加Basic Authentication认证
// httpPost
httpPost.addHeader(“Authorization”, "Basic " + Base64.encodeBase64String(“username:password”.getBytes()));
// httpConnection
httpConn.setRequestProperty(“Authorization”, "Basic " + Base64.encodeBase64String(“username:password”.getBytes()));

方式二:使用Authenticator重写getPasswordAuthentication()–无测试过

相关jar包


      org.apache.httpcomponents
      httpclient
      4.5

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**

  • Created by BugRoot
    */
    public class HttpUtils {

    /**

    • Post请求webservice 带http认证

    • @param url 请求地址

    • @param param 请求参数

    • @param SOAPAction SOAPAction 接口–如不需请注释

    • @return
      */
      public static String httpClientPostSOAPActionAndAuth(String url, String param, String username,String password,String SOAPAction){
      System.out.println(param);
      CloseableHttpClient http = HttpClientBuilder.create().setProxy(new HttpHost(“127.0.0.1”,1081)).build();// 测试环境–本地代理方式
      // CloseableHttpClient http = HttpClientBuilder.create().build();// 生产环境–部署到服务器
      HttpPost httpPost = new HttpPost(url);
      CloseableHttpResponse res = null;
      String entity = “”;
      // 请求错误
      String errorMessage="";
      try {
      // 下述方式不推荐,BASE64Encoder和BASE64Decoder这两个方法是sun公司的内部方法,没有 在java api中公开过, 使用这些方法是不安全的
      // String token = username +":"+ password;
      // BASE64Encoder base64en = new BASE64Encoder();
      // token = base64en.encode(token.getBytes(“utf-8”));
      // token = "Basic " + token;
      // System.out.println(token);
      // 建议使用apache的API-可引用import org.apache.commons.codec.binary.Base64;进行替换
      我使用的是java.util的
      String token = “Basic " + “Basic " + Base64.getEncoder().encodeToString(username +”:”+password.getBytes(StandardCharsets.UTF_8));
      StringEntity s = new StringEntity(param, “UTF-8”);
      //s.setContentEncoding(“UTF-8”);
      // s.setContentType(“text/xml”);//发送json数据需要设置contentType
      // s.setContentType(“application/xml”);//发送json数据需要设置contentType
      httpPost.setHeader(“Accept-Encoding”,“gzip,deflate”);
      httpPost.setHeader(“Content-Type”,“text/xml”);
      httpPost.setHeader(“SOAPAction”,SOAPAction); //设置接口方法名–如不需请注释
      httpPost.setHeader(“Host”,“devwebservices.purolator.com”);
      httpPost.setHeader(“Connection”,“Keep-Alive”);
      httpPost.setHeader(“Accept-Encoding”,“gzip,deflate”);
      httpPost.setHeader(“User-Agent”,“Apache-HttpClient/4.1.1 (java 1.5)”);
      // httpPost.setHeader(“Authorization”,token);
      httpPost.setHeader(“Authorization”,“Basic ZmYxOWY0ZTBmZDhmNDE0NTllNjI0M2Q5ZTZmYmJkMTY6dUs3Ln14cCg=”);
      httpPost.setEntity(s);
      res = http.execute(httpPost);
      HttpEntity responseEntity = res.getEntity();
      System.out.println(“response status” + res.getStatusLine());

       // 获取状态码
       int statusCod = res.getStatusLine().getStatusCode();
       if(statusCod > 200){
           // TODO: 2020/7/24
       }
       // 解析响应报文 TODO
       if (responseEntity != null) {
           System.out.println("response length:" + responseEntity.getContentLength());
           entity = EntityUtils.toString(responseEntity);
           System.out.println("response content:" + entity);
      
       } else {
           errorMessage = "service exception";
       }
      

      } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      } finally {
      try {
      http.close();
      res.close();
      } catch (IOException e) {
      e.printStackTrace();
      }

      }

      return entity;
      }
      }

你可能感兴趣的:(Utils,java)