JAVA HttpClient 远程调用接口doGet、doPost工具类,面试必备三句话

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip1024b (备注Java)
img

正文

// bodys.put(“sn”,“SN666666666”);

// String jsonStr= JSONObject.toJSONString(bodys);

//

// HttpResponse response = HttpsUtils.doPost(IP, path,“POST”, headers, querys,jsonStr);

// 得到返回的参数

// String getResponse = EntityUtils.toString(response.getEntity());

//

// return getResponse;

// }

/**

  • basic auth认证 Get方式

*/

public static String doGetWithBasicAuth(String url, String basic_userName, String basic_password) throws IOException {

// 创建HttpClientBuilder

HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

// 设置BasicAuth

CredentialsProvider provider = new BasicCredentialsProvider();

// Create the authentication scope

AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

// Create credential pair,在此处填写用户名和密码

UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(basic_userName, basic_password);

// Inject the credentials

provider.setCredentials(scope, credentials);

// Set the default credentials provider

httpClientBuilder.setDefaultCredentialsProvider(provider);

// HttpClient

CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

String result = “”;

HttpGet httpGet = null;

HttpResponse httpResponse = null;

HttpEntity entity = null;

httpGet = new HttpGet(url);

try {

httpResponse = closeableHttpClient.execute(httpGet);

entity = httpResponse.getEntity();

if (entity != null) {

result = EntityUtils.toString(entity);

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

// 关闭连接

closeableHttpClient.close();

return result;

}

/**

  • 调用举例

*/

// String url = “http://140.xxx.22.xxx:18089/apxxx/” + vin;

// //basic auth中的用户名和密码

// String basic_userName = “admin”;

// String basic_password = “public”;

// 得到返回的参数

// String resultStr = HttpClientUtilCIV.doGetWithBasicAuth(url, basic_userName, basic_password);

/**

  • post form(传递的是用&符号连接的字符串,@RequestBody String testData可以接收)

  • 对于得到参数格式为:vin=111&sn=12335

  • @param host

  • @param path

  • @param headers

  • @param querys

  • @param bodys

  • @return

  • @throws Exception

*/

public static HttpResponse doPost(String host, String path,

Map<String, String> headers,

Map<String, String> querys,

Map<String, String> bodys)

throws Exception {

HttpClient httpClient = wrapClient(host);

HttpPost request = new HttpPost(buildUrl(host, path, querys));

for (Map.Entry<String, String> e : headers.entrySet()) {

request.addHeader(e.getKey(), e.getValue());

}

if (bodys != null) {

List nameValuePairList = new ArrayList();

for (String key : bodys.keySet()) {

nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));

}

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, “utf-8”);

formEntity.setContentType(“application/x-www-form-urlencoded; charset=UTF-8”);

request.setEntity(formEntity);

}

return httpClient.execute(request);

}

/**

  • Post stream

  • @param host

  • @param path

  • @param method

  • @param headers

  • @param querys

  • @param body

  • @return

  • @throws Exception

*/

public static HttpResponse doPost(String host, String path, String method,

Map<String, String> headers,

Map<String, String> querys,

byte[] body)

throws Exception {

HttpClient httpClient = wrapClient(host);

HttpPost request = new HttpPost(buildUrl(host, path, querys));

for (Map.Entry<String, String> e : headers.entrySet()) {

request.addHeader(e.getKey(), e.getValue());

}

if (body != null) {

request.setEntity(new ByteArrayEntity(body));

}

return httpClient.execute(request);

}

/**

  • Put String

  • @param host

  • @param path

  • @param method

  • @param headers

  • @param querys

  • @param body

  • @return

  • @throws Exception

*/

public static HttpResponse doPut(String host, String path, String method,

Map<String, String> headers,

Map<String, String> querys,

String body)

throws Exception {

HttpClient httpClient = wrapClient(host);

HttpPut request = new HttpPut(buildUrl(host, path, querys));

for (Map.Entry<String, String> e : headers.entrySet()) {

request.addHeader(e.getKey(), e.getValue());

}

if (StringUtils.isNotBlank(body)) {

request.setEntity(new StringEntity(body, “utf-8”));

}

return httpClient.execute(request);

}

/**

  • Put stream

  • @param host

  • @param path

  • @param method

  • @param headers

  • @param querys

  • @param body

  • @return

  • @throws Exception

*/

public static HttpResponse doPut(String host, String path, String method,

Map<String, String> headers,

Map<String, String> querys,

byte[] body)

throws Exception {

HttpClient httpClient = wrapClient(host);

HttpPut request = new HttpPut(buildUrl(host, path, querys));

for (Map.Entry<String, String> e : headers.entrySet()) {

request.addHeader(e.getKey(), e.getValue());

}

if (body != null) {

request.setEntity(new ByteArrayEntity(body));

}

return httpClient.execute(request);

}

/**

  • Delete

  • @param host

  • @param path

  • @param method

  • @param headers

  • @param querys

  • @return

  • @throws Exception

*/

public static HttpResponse doDelete(String host, String path, String method,

Map<String, String> headers,

Map<String, String> querys)

throws Exception {

HttpClient httpClient = wrapClient(host);

HttpDelete request = new HttpDelete(buildUrl(host, path, querys));

for (Map.Entry<String, String> e : headers.entrySet()) {

request.addHeader(e.getKey(), e.getValue());

}

return httpClient.execute(request);

}

@SuppressWarnings(“resource”)

public static String doPost(String host, String path,String jsonstr,String charset){

String url=host+path;

HttpClient httpClient = null;

HttpPost httpPost = null;

String result = null;

try{

httpClient = wrapClient(host);

//------------------------------4.1,4.2 版本设置时间-----------------------------

//设置连接时间

httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);

//设置数据传输时间

httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);

httpPost = new HttpPost(url);

httpPost.addHeader(“Content-Type”, “application/json”);

//此处是将请求体封装成为了StringEntity,若乱码则指定utf-8

//StringEntity se = new StringEntity(jsonstr,“utf-8”);

StringEntity se = new StringEntity(jsonstr);

se.setContentType(“text/json”);

se.setContentEncoding(new BasicHeader(“Content-Type”, “application/json”));

httpPost.setEntity(se);

HttpResponse response = httpClient.execute(httpPost);

if(response != null){

HttpEntity resEntity = response.getEntity();

if(resEntity != null){

result = EntityUtils.toString(resEntity,charset);

}

}

}catch(Exception ex){

// ex.printStackTrace();

//连接超时或者数据传输时间超时

String apiResult=“timeOut”;

return apiResult;

}

return result;

}

/**

*doPost 举例

*/

// String IP = “http://localhost:8075”;

// String path=“/testPostTest”;

// Map<String, String> bodys = new HashMap<String, String>();

// bodys.put(“vin”,“VIN223333”);

// bodys.put(“sn”,“SN666666666”);

// String jsonStr= JSONObject.toJSONString(bodys);

// String resultStr= HttpsUtils.doPost(IP,path,jsonStr, “utf-8”);

// return resultStr;

// }

/**

  • 拼接url

  • @param host

  • @param path

  • @param querys

  • @return

  • @throws UnsupportedEncodingException

*/

private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {

StringBuilder sbUrl = new StringBuilder();

sbUrl.append(host);

if (!StringUtils.isBlank(path)) {

sbUrl.append(path);

}

if (null != querys) {

StringBuilder sbQuery = new StringBuilder();

for (Map.Entry<String, String> query : querys.entrySet()) {

if (0 < sbQuery.length()) {

sbQuery.append(“&”);

}

if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {

sbQuery.append(query.getValue());

}

if (!StringUtils.isBlank(query.getKey())) {

sbQuery.append(query.getKey());

if (!StringUtils.isBlank(query.getValue())) {

sbQuery.append(“=”);

sbQuery.append(URLEncoder.encode(query.getValue(), “utf-8”));

}

}

}

if (0 < sbQuery.length()) {

sbUrl.append(“?”).append(sbQuery);

}

}

return sbUrl.toString();

}

private static HttpClient wrapClient(String host) {

HttpClient httpClient = new DefaultHttpClient();

if (host.startsWith(“https://”)) {

sslClient(httpClient);

}

return httpClient;

}

private static void sslClient(HttpClient httpClient) {

try {

SSLContext ctx = SSLContext.getInstance(“TLS”);

X509TrustManager tm = new X509TrustManager() {

@Override

public X509Certificate[] getAcceptedIssuers() {

return null;

}

@Override

public void checkClientTrusted(X509Certificate[] xcs, String str) {

}

@Override

public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

}

};

ctx.init(null, new TrustManager[] { tm }, null);

SSLSocketFactory ssf = new SSLSocketFactory(ctx);

ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

ClientConnectionManager ccm = httpClient.getConnectionManager();

SchemeRegistry registry = ccm.getSchemeRegistry();

registry.register(new Scheme(“https”, 443, ssf));

} catch (KeyManagementException ex) {

throw new RuntimeException(ex);

} catch (NoSuchAlgorithmException ex) {

throw new RuntimeException(ex);

}

}

接下来这个工具类是post请求,里面有关于设置BASEAUTH 认证的,

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.ParseException;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

Kafka进阶篇知识点

image

Kafka高级篇知识点

image

44个Kafka知识点(基础+进阶+高级)解析如下

image

由于篇幅有限,小编已将上面介绍的**《Kafka源码解析与实战》、Kafka面试专题解析、复习学习必备44个Kafka知识点(基础+进阶+高级)都整理成册,全部都是PDF文档**

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

eException;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

Kafka进阶篇知识点

[外链图片转存中…(img-6l9yUlQy-1713604778967)]

Kafka高级篇知识点

[外链图片转存中…(img-SqVjuNGD-1713604778968)]

44个Kafka知识点(基础+进阶+高级)解析如下

[外链图片转存中…(img-DxKlEvZq-1713604778968)]

由于篇幅有限,小编已将上面介绍的**《Kafka源码解析与实战》、Kafka面试专题解析、复习学习必备44个Kafka知识点(基础+进阶+高级)都整理成册,全部都是PDF文档**

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip1024b (备注Java)
[外链图片转存中…(img-bOlY4t2K-1713604778969)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值