HTTPClient调用https请求,通过基本认证用户名密码(Basic Auth)

2023-05-16

本文来源是Apache官网例子:

httpcomponents-client/ClientAuthentication.java at 4.5.x · apache/httpcomponents-client · GitHub

之前找过很多博客上的例子发现都不对,后来还是去官网找。事实证明官网绝对比博客k

例子:

//https://github.com/apache/httpcomponents-client/blob/4.5.x/httpclient/src/examples/org/apache/http/examples/client/ClientAuthentication.java

/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package org.apache.http.examples.client;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.util.EntityUtils;

/**
 * A simple example that uses HttpClient to execute an HTTP request against
 * a target site that requires user authentication.
 */
public class ClientAuthentication {

    public static void main(String[] args) throws Exception {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope("httpbin.org", 80),
                new UsernamePasswordCredentials("user", "passwd"));
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build();
        try {
            HttpGet httpget = new HttpGet("http://httpbin.org/basic-auth/user/passwd");

            System.out.println("Executing request " + httpget.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

//下面是正常http请求,直接发送json格式的作为参数传到服务器
HttpPost post = new HttpPost(url);
		//post.setHeader("Content-Type","application/json;charset=utf-8");
		StringEntity entity = new StringEntity(obj.toString(),"utf-8");
		entity.setContentEncoding("UTF-8");    
		entity.setContentType("application/json");  
		
		post.setEntity(entity);
		CloseableHttpClient createDefault = HttpClients.createDefault();
		CloseableHttpResponse result = createDefault.execute(post);
		String responseMsg = EntityUtils.toString(result.getEntity(),"UTF-8"));

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

HTTPClient调用https请求,通过基本认证用户名密码(Basic Auth) 的相关文章

随机推荐

  • 51单片机串口通讯UART

    1 串行通信的的基本知识 在实际的工业生产 xff0c 或者生活中 xff0c 计算机的CPU要与外部的设备之间进行信息的交流 xff0c 数据的交换 xff0c 所有的这些信息交换均可称为通信 通信的方式有两种 xff0c 分别为串行通信
  • 库函数开发与寄存器开发

    在以前 8 位机时代的程序开发中 xff0c 一般直接配置芯片的寄存器 xff0c 控制芯片的工作方式 xff0c 如中断 xff0c 定时器等 配置的时候 xff0c 常常要查阅寄存器表 xff0c 看用到哪些配置位 xff0c 为了配置
  • Arduino修改Serial接收缓冲区大小

    看到网上有资料说 xff0c 直接添加以下宏定义就可以了 xff1a span class token macro property span class token directive keyword define span SERIAL
  • RT-Thread nmealib库WH-GN100模块设置仅支持北斗

    RT Thread nmealib库主页 在nmea thread init函数的末尾 xff0c 添加以下代码块 xff0c 发送配置指令 xff0c 仅使用北斗卫星 xff0c 即可配置成仅GPS卫星工作模式 span class to
  • C#中字符串判断为空或者空格

    最近遇到这个问题 xff0c 来大概说一下C 中字符串判断为空或者空格这个问题 xff08 1 xff09 字符串为空null xff0c 怎么讲就是内存中没有放东西 xff0c 比如新创建的字符串就为空null xff0c string
  • 【冷知识】火车票座位分布知识点

    最近到了每年过年 xff0c 春运火车高峰期的时候了 xff0c 有的人想知道自己具体的位置在哪里 xff08 比如硬座是不是靠窗的 xff0c 座位的大小号排序等 xff09 xff0c 现在来讲讲这方面的知识点 xff0c 个人整理 列
  • QT中的自定义信号以及自定义函数

    信号与槽函数是QT的一大创新 xff0c 通过自定义信号与槽函数可以实现自己想实现的功能 标准的信号与槽写法如下 xff1a connect amp button amp QPushButton clicked this amp QWidg
  • 如何摆放PCB元器件?(建议收藏)

    PCB设计 xff0c 既是科学也是艺术 其中有非常多关于布线线宽 布线叠层 原理图等等相关的技术规范 xff0c 但当你涉及到PCB设计中具有艺术特质元器件布局问题时 xff0c 问题就变得有趣起来了 事实上 xff0c 关于元器件摆放限
  • 【MFC开发(6)】复选框按钮控件Check Box

    1 新建复选框 直接拖拽即可 xff0c 设置名字可修改caption内容 2 设置默认选中 复选框可多选 xff0c 所以可以给很多复选框按钮进行选中 xff0c 代码如下所示 xff0c 放在dlg初始化函数中实现 获取多选框香蕉的指针
  • 【MFC开发(15)】进度条控件Progress Control

    1 进度条控件的常用方法 首先给控件添加一个变量 在dlg初始化函数钟进行方法的实现 进度条显示区域 设置进度条的范围 m progress SetRange 0 100 设置进度条当前的位置 m progress SetPos 75 获取
  • 【MFC开发(16)】树形控件Tree Control

    1 树形控件的属性配置 xff08 1 xff09 Check Boxes xff1a 默认为false xff0c 如果选择为true的话每个节点前面会带有一个方框 xff08 2 xff09 Edit Labels xff1a 默认为f
  • 【MFC开发(17)】高级列表控件List Control

    1 介绍 ListCtrl 高级列表控件也是我们平时编程过程中很常用的一个控件 xff0c 一般涉及到报表展示 记录展示之类的 xff0c 都需要ListCtrl 高级列表控件 例如 xff1a 任务管理器啊 xff0c 文件列表啊 xff
  • STM32L4单片机连接语音模块NVC的源码

    这周写了一下STM32L4的语音模块 xff0c 使用的语音芯片是NVC系列芯片 xff0c 提供一下代码给以后需要的朋友们 xff0c 不喜勿喷 头文件NVC h ifndef NVC H define NVC H 音源 define S
  • oled显示模块ssd1306

    管脚定义 GND 电源地 VCC xff1a 供电电源3 3v 5v都可以 D0 xff1a 串行输入时钟CLK D1 xff1a 串行输入数据 RES xff1a 复位 DC xff1a 控制输入数据 命令 xff08 高电平1为数据 低
  • 上位机串口数据检验方式(一)——校验和

    最近还是在写上位机软件 xff0c 还是有一堆问题 xff0c 因为是第一次做这个东西 xff0c 有些东西只能到论坛上来查 xff0c 最近做到了数据通信 xff0c 刚开始没有想到数据协议这些东西 xff0c 现在涉及到了 xff0c
  • c#上位机开发(三)——串口通信上位机开发1

    今天主要做一个跟市面上差不多的稍微简单点的上位机软件 xff0c 效果如下图所示 1 功能概述 xff08 1 xff09 端口扫描 xff0c 主要是扫描出可用的端口用来连接 xff08 2 xff09 波特率的选择 xff0c 使用一个
  • 使用python执行外部命令subprocess

    1 使用python执行外部命令subprocess subprocess模块是Python自带的模块 xff0c 无须再另行安装 xff0c 它主要用来取代一些旧的模块或方法 xff0c 如os system os spawn os po
  • #Qt on android#使用Qt 获取GPS信号

    注意事项 xff1a 1 Qt版本一定要大于等于5 3 xff0c 因为低于5 3的版本对于android系统来说并不能成功获取gps信号 2 环境正确搭建 xff0c 一定要注意 xff01 构建 xff08 build xff09 的系
  • 2023年TI杯全国大学生电子设计竞赛通知正式发布

    关于组织2023年 全国大学生电子设计竞赛的通知 xff08 电组字 2023 01号 xff09 各赛区组织委员会 各有关高等学校 xff1a 全国大学生电子设计竞赛 xff08 以下简称全国竞赛 xff09 组委会在认真总结往届电子设计
  • HTTPClient调用https请求,通过基本认证用户名密码(Basic Auth)

    本文来源是Apache官网例子 xff1a httpcomponents client ClientAuthentication java at 4 5 x apache httpcomponents client GitHub 之前找过很