base64加密方式认证方式下的basic auth。
注意 base64的basic auth 使用
httpclient自带的认证方式如下会认证失败:
credentialsprovider provider = new basiccredentialsprovider();usernamepasswordcredentials credentials = new usernamepasswordcredentials("username", "user1pass");provider.setcredentials(authscope.any, credentials);httpclient client = httpclientbuilder.create() .setdefaultcredentialsprovider(provider) .build();
成功通过的例子:
package com.biologic.api.service.impl;import java.io.ioexception;import java.util.base64;import java.util.map;import org.apache.http.httpentity;import org.apache.http.httpresponse;import org.apache.http.client.clientprotocolexception;import org.apache.http.client.methods.httppost;import org.apache.http.entity.contenttype;import org.apache.http.entity.mime.multipartentitybuilder;import org.apache.http.entity.mime.content.stringbody;import org.apache.http.impl.client.closeablehttpclient;import org.apache.http.impl.client.httpclientbuilder;import org.apache.http.util.entityutils;import org.springframework.stereotype.service;import com.biologic.api.service.httpservice;@servicepublic class httpserviceimpl implements httpservice { @override public int httpclientwithbasicauth(string username, string password, string uri, map<string, string> parammap) { try { // 创建httpclientbuilder httpclientbuilder httpclientbuilder = httpclientbuilder.create(); closeablehttpclient closeablehttpclient = httpclientbuilder.build(); httppost httppost = new httppost(uri); //添加http头信息 httppost.addheader("authorization", "basic " + base64.geturlencoder().encodetostring((username + ":" + password).getbytes())); multipartentitybuilder builder = multipartentitybuilder.create(); parammap.foreach((k,v)->{ builder.addpart(k, new stringbody(v, contenttype.multipart_form_data)); }); httpentity postentity = builder.build(); httppost.setentity(postentity); string result = ""; httpresponse httpresponse = null; httpentity entity = null; try { httpresponse = closeablehttpclient.execute(httppost); entity = httpresponse.getentity(); if( entity != null ){ result = entityutils.tostring(entity); } } catch (clientprotocolexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } // 关闭连接 closeablehttpclient.close(); system.out.println(result); }catch (exception e) { system.out.println(e.getstacktrace()); } return 0; }}
相关文章:
java发送post请求的实例代码分享
java使用原生发送http请求的实例
相关视频:
全面解析java注解
以上就是java发送带basic auth使用 httpclient自带的认证方式的详细内容。