热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用User-Agent防止HttpClient发送http请求时403Forbidden和安全拦截

之前写过一个Java工具类–通过HttpClient发送http请求最近在访问一个接口的时候被拒绝了。具体信息如下我们用程序访问我的csdn博客地址解决方案就是在httpclient发

之前写过一个Java工具类–通过HttpClient发送http请求

最近在访问一个接口的时候被拒绝了。具体信息如下

这里写图片描述

我们用程序访问我的csdn博客地址

这里写图片描述

解决方案就是在httpclient发出请求的时候在Header中设置一个User-Agent

HTTP响应头和请求头信息对照表

具体如下

    String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("User-Agent",userAgent);
response = httpclient.execute(httpGet);

我电脑的谷歌浏览器User-Agent

这里写图片描述

加上User-Agent之后访问我的博客地址

这里写图片描述

完整的代码

HttpUtil.java

package com.jrbac.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Http工具类,发送Http请求, Get请求请将参数放在url中 Post请求请将参数放在Map中
*
* @author 程高伟
* @date 2017年1月5日 下午6:03:50
*/

public class HttpUtil {
private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);
private static final CloseableHttpClient httpclient = HttpClients.createDefault();
private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";

/**
* 发送HttpGet请求
*
* @param url
* 请求地址
* @return 返回字符串
*/

public static String sendGet(String url) {
String result = null;
CloseableHttpResponse respOnse= null;
try {
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("User-Agent", userAgent);
respOnse= httpclient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
} catch (Exception e) {
log.error("处理失败 {}" + e);
e.printStackTrace();
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
return result;
}

/**
* 发送HttpPost请求,参数为map
*
* @param url
* 请求地址
* @param map
* 请求参数
* @return 返回字符串
*/

public static String sendPost(String url, Map map) {
// 设置参数
List formparams = new ArrayList();
for (Map.Entry entry : map.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
// 编码
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
// 取得HttpPost对象
HttpPost httpPost = new HttpPost(url);
// 防止被当成攻击添加的
httpPost.setHeader("User-Agent", userAgent);
// 参数放入Entity
httpPost.setEntity(formEntity);
CloseableHttpResponse respOnse= null;
String result = null;
try {
// 执行post请求
respOnse= httpclient.execute(httpPost);
// 得到entity
HttpEntity entity = response.getEntity();
// 得到字符串
result = EntityUtils.toString(entity);
} catch (IOException e) {
log.error(e.getMessage());
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
return result;
}

/**
* 发送HttpPost请求,参数为文件,适用于微信上传素材
*
* @param url
* 请求地址
* @param file
* 上传的文件
* @return 返回字符串
* @throws IOException
* @throws ClientProtocolException
*/

public static String sendPost(String url, File file) {
String result = null;
HttpPost httpPost = new HttpPost(url);
// 防止被当成攻击添加的
httpPost.setHeader("User-Agent", userAgent);
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("media", new FileBody(file));
httpPost.setEntity(multipartEntity.build());
CloseableHttpResponse respOnse= null;
try {
respOnse= httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (IOException e) {
log.error(e.getMessage());
} finally {
// 关闭CloseableHttpResponse
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
return result;

}

/**
* 发送HttpPost请求,参数为json字符串
*
* @param url
* @param jsonStr
* @return
*/

public static String sendPost(String url, String jsonStr) {
String result = null;
// 字符串编码
StringEntity entity = new StringEntity(jsonStr, Consts.UTF_8);
// 设置content-type
entity.setContentType("application/json");
HttpPost httpPost = new HttpPost(url);
// 防止被当成攻击添加的
httpPost.setHeader("User-Agent", userAgent);
httpPost.setEntity(entity);
CloseableHttpResponse respOnse= null;
try {
respOnse= httpclient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (IOException e) {
log.error(e.getMessage());
} finally {
// 关闭CloseableHttpResponse
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
return result;
}

/**
* 发送不带参数的HttpPost请求
*
* @param url
* @return
*/

public static String sendPost(String url) {
String result = null;
// 得到一个HttpPost对象
HttpPost httpPost = new HttpPost(url);
// 防止被当成攻击添加的
httpPost.setHeader("User-Agent", userAgent);
CloseableHttpResponse respOnse= null;
try {
// 执行HttpPost请求,并得到一个CloseableHttpResponse
respOnse= httpclient.execute(httpPost);
// 从CloseableHttpResponse中拿到HttpEntity
HttpEntity entity = response.getEntity();
// 将HttpEntity转换为字符串
result = EntityUtils.toString(entity);
} catch (IOException e) {
log.error(e.getMessage());
} finally {
// 关闭CloseableHttpResponse
if (response != null) {
try {
response.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
return result;
}
}

参考文献

HTTP响应头和请求头信息对照表


推荐阅读
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 使用Ubuntu中的Python获取浏览器历史记录原文: ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • Ubuntu安装常用软件详细步骤
    目录1.GoogleChrome浏览器2.搜狗拼音输入法3.Pycharm4.Clion5.其他软件1.GoogleChrome浏览器通过直接下载安装GoogleChro ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 本文讨论了在openwrt-17.01版本中,mt7628设备上初始化启动时eth0的mac地址总是随机生成的问题。每次随机生成的eth0的mac地址都会写到/sys/class/net/eth0/address目录下,而openwrt-17.01原版的SDK会根据随机生成的eth0的mac地址再生成eth0.1、eth0.2等,生成后的mac地址会保存在/etc/config/network下。 ... [详细]
  • 本文介绍了如何使用Express App提供静态文件,同时提到了一些不需要使用的文件,如package.json和/.ssh/known_hosts,并解释了为什么app.get('*')无法捕获所有请求以及为什么app.use(express.static(__dirname))可能会提供不需要的文件。 ... [详细]
  • CEPH LIO iSCSI Gateway及其使用参考文档
    本文介绍了CEPH LIO iSCSI Gateway以及使用该网关的参考文档,包括Ceph Block Device、CEPH ISCSI GATEWAY、USING AN ISCSI GATEWAY等。同时提供了多个参考链接,详细介绍了CEPH LIO iSCSI Gateway的配置和使用方法。 ... [详细]
  • 本文讨论了编写可保护的代码的重要性,包括提高代码的可读性、可调试性和直观性。同时介绍了优化代码的方法,如代码格式化、解释函数和提炼函数等。还提到了一些常见的坏代码味道,如不规范的命名、重复代码、过长的函数和参数列表等。最后,介绍了如何处理数据泥团和进行函数重构,以提高代码质量和可维护性。 ... [详细]
  • Android系统源码分析Zygote和SystemServer启动过程详解
    本文详细解析了Android系统源码中Zygote和SystemServer的启动过程。首先介绍了系统framework层启动的内容,帮助理解四大组件的启动和管理过程。接着介绍了AMS、PMS等系统服务的作用和调用方式。然后详细分析了Zygote的启动过程,解释了Zygote在Android启动过程中的决定作用。最后通过时序图展示了整个过程。 ... [详细]
  • 本文介绍了在CentOS 6.4系统中更新源地址的方法,包括备份现有源文件、下载163源、修改文件名、更新列表和系统,并提供了相应的命令。 ... [详细]
  • 如何在HTML中获取鼠标的当前位置
    本文介绍了在HTML中获取鼠标当前位置的三种方法,分别是相对于屏幕的位置、相对于窗口的位置以及考虑了页面滚动因素的位置。通过这些方法可以准确获取鼠标的坐标信息。 ... [详细]
  • 本文介绍了网页播放视频的三种实现方式,分别是使用html5的video标签、使用flash来播放以及使用object标签。其中,推荐使用html5的video标签来简单播放视频,但有些老的浏览器不支持html5。另外,还可以使用flash来播放视频,需要使用object标签。 ... [详细]
  • 本文整理了常用的CSS属性及用法,包括背景属性、边框属性、尺寸属性、可伸缩框属性、字体属性和文本属性等,方便开发者查阅和使用。 ... [详细]
author-avatar
真个田_707
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有