
[java] view plain copy
//处理http请求 requestUrl为请求地址 requestMethod请求方式,值为"GET"或"POST"
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null
try{
URL url=new URL(requestUrl)
HttpURLConnection conn=(HttpURLConnection)url.openConnection()
conn.setDoOutput(true)
conn.setDoInput(true)
conn.setRequestMethod(requestMethod)
conn.connect()
//往服务器端写内容 也就是发起http请求需要带的参数
if(null!=outputStr){
OutputStream os=conn.getOutputStream()
os.write(outputStr.getBytes("utf-8"))
os.close()
}
//读取服务器端返回的内容
InputStream is=conn.getInputStream()
InputStreamReader isr=new InputStreamReader(is,"utf-8")
BufferedReader br=new BufferedReader(isr)
buffer=new StringBuffer()
String line=null
while((line=br.readLine())!=null){
buffer.append(line)
}
}catch(Exception e){
e.printStackTrace()
}
return buffer.toString()
}
2.测试。
[java] view plain copy
public static void main(String[] args){
String s=httpRequest("","GET",null)
System.out.println(s)
}
输出结果为的源代码,说明请求成功。
注:1).第一个参数url需要写全地址,即前边的http必须写上,不能只写这样的。
2).第二个参数是请求方式,一般接口调用会给出URL和请求方式说明。
3).第三个参数是我们在发起请求的时候传递参数到所要请求的服务器,要传递的参数也要看接口文档确定格式,一般是封装成json或xml.
4).返回内容是String类,但是一般是有格式的json或者xml。
二:发起https请求。
1.https是对链接加了安全证书SSL的,如果服务器中没有相关链接的SSL证书,它就不能够信任那个链接,也就不会访问到了。所以我们第一步是自定义一个信任管理器。自要实现自带的X509TrustManager接口就可以了。
[java] view plain copy
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.X509TrustManager
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null
}
}
注:1)需要的包都是java自带的,所以不用引入额外的包。
2.)可以看到里面的方法都是空的,当方法为空是默认为所有的链接都为安全,也就是所有的链接都能够访问到。当然这样有一定的安全风险,可以根据实际需要写入内容。
2.编写https请求方法。
[java] view plain copy
/*
* 处理https GET/POST请求
* 请求地址、请求方法、参数
* */
public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null
try{
//创建SSLContext
SSLContext sslContext=SSLContext.getInstance("SSL")
TrustManager[] tm={new MyX509TrustManager()}
//初始化
sslContext.init(null, tm, new java.security.SecureRandom())
//获取SSLSocketFactory对象
SSLSocketFactory ssf=sslContext.getSocketFactory()
URL url=new URL(requestUrl)
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection()
conn.setDoOutput(true)
conn.setDoInput(true)
conn.setUseCaches(false)
conn.setRequestMethod(requestMethod)
//设置当前实例使用的SSLSoctetFactory
conn.setSSLSocketFactory(ssf)
conn.connect()
//往服务器端写内容
if(null!=outputStr){
OutputStream os=conn.getOutputStream()
os.write(outputStr.getBytes("utf-8"))
os.close()
}
//读取服务器端返回的内容
InputStream is=conn.getInputStream()
InputStreamReader isr=new InputStreamReader(is,"utf-8")
BufferedReader br=new BufferedReader(isr)
buffer=new StringBuffer()
String line=null
while((line=br.readLine())!=null){
buffer.append(line)
}
}catch(Exception e){
e.printStackTrace()
}
return buffer.toString()
}
可见和http访问的方法类似,只是多了SSL的相关处理。
3.测试。先用http请求的方法访问,再用https的请求方法访问,进行对比。
http访问:
[java] view plain copy
public static void main(String[] args){
String s=httpRequest("","GET",null)
System.out.println(s)
}
结果为:
https访问:
[java] view plain copy
public static void main(String[] args){
String s=httpsRequest("","GET",null)
System.out.println(s)
}
结果为:
可见https的链接一定要进行SSL的验证或者过滤之后才能够访问。
三:https的另一种访问方式——导入服务端的安全证书。
1.下载需要访问的链接所需要的安全证书。 以这个网址为例。
1)在浏览器上访问。
2)点击上图的那个打了×的锁查看证书。
3)选择复制到文件进行导出,我们把它导入到java项目所使用的jre的lib文件下的security文件夹中去,我的是这个路径。D:\Program Files (x86)\Java\jre8\lib\security
注:中间需要选导出格式,就选默认的就行,还需要命名,我命名的是12306.
2.打开cmd,进入到java项目所使用的jre的lib文件下的security目录。
3.在命令行输入 Keytool -import -alias 12306 -file 12306.cer -keystore cacerts
4.回车后会让输入口令,一般默认是changeit,输入时不显示,输入完直接按回车,会让确认是否信任该证书,输入y,就会提示导入成功。
5.导入成功后就能像请求http一样请求https了。
测试:
[java] view plain copy
public static void main(String[] args){
String s=httpRequest("","GET",null)
System.out.println(s)
}
结果:
现在就可以用http的方法请求https了。
注:有时候这一步还是会出错,那可能是jre的版本不对,我们右键run as——run configurations,选择证书所在的jre之后再运行。
首先,我们先看一下http的头信息到底是什么:HTTP(HyperTextTransferProtocol) 即超文本传输协议,目前网页传输的的通用协议。HTTP协议采用了请求/响应模型,浏览器或其他客户端发出请求,服务器给与响应。就整个网络资源传输而 言,包括message-header和message-body两部分。首先传递message- header,即http header消息。http header 消息通常被分为4个部分: general header, request header, response header, entity header。但是这种分法就理解而言,感觉界限不太明确,根据日常使用,大体分为Request和Response两部分。
在通常的servlet/jsp应用中,我们只是从http的header中取得信息,如果要设置信息,需要用到HttpClient,具体的设置方法如下:
HttpResponse response = null
HttpGet get = new HttpGet(url)
get.addHeader("Accept", "text/html")
get.addHeader("Accept-Charset", "utf-8")
get.addHeader("Accept-Encoding", "gzip")
get.addHeader("Accept-Language", "en-US,en")
get.addHeader("User-Agent", "Mozilla/5.0 (X11Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22")
response = client.execute(get)
HttpEntity entity = response.getEntity()
Header header = entity.getContentEncoding()
if (header != null)
{
HeaderElement[] codecs = header.getElements()
for (int i = 0i <codecs.lengthi++)
{
if (codecs[i].getName().equalsIgnoreCase("gzip"))
{
response.setEntity(new GzipDecompressingEntity(entity))
}
}
}
return response
其中,client为一个HttpClient的实力,创建方式如:
SchemeRegistry schemeRegistry = new SchemeRegistry()
schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()))
schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()))
PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry)
cm.setMaxTotal(200)
cm.setDefaultMaxPerRoute(2)
HttpHost googleResearch = new HttpHost("research.google.com", 80)
HttpHost wikipediaEn = new HttpHost("en.wikipedia.org", 80)
cm.setMaxPerRoute(new HttpRoute(googleResearch), 30)
cm.setMaxPerRoute(new HttpRoute(wikipediaEn), 50)
DefaultHttpClient client = new DefaultHttpClient(cm)
实现思路就是先定义请求头内容,之后进行请求头设置。
定义请求头
LinkedHashMap<String,String>headers = new LinkedHashMap<String,String>()
headers.put("Content-type","text/xml")
headers.put("Cache-Control", "no-cache")
headers.put("Connection", "close")
给HttpPost 设置请求头
HttpPost httpPost = new HttpPost("http://localhost:8080/root")
if (headers != null) {
for (String key : headers.keySet()) {
httpPost.setHeader(key, headers.get(key))
}
}
备注:只需要在map中设置相应的请求头内容即可。根据实际需要修改即可
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)