发送HTTPS请求,获得网页内容的java方法
java模拟httphttpspost请求
java模拟httphttpspost请求1.Post请求失败的代码try {HttpResponse response = httpClient.execute(httpPost);HttpEntity entity = response.getEntity();result = EntityUtils.toString(entity, "UTF-8");Util.log("API,POST回来的数据是:");Util.log(result);} catch (ConnectionPoolTimeoutException e) {log.e("http get throw ConnectionPoolTimeoutException(wait time out)");} catch (ConnectTimeoutException e) {log.e("http get throw ConnectTimeoutException");} catch (SocketTimeoutException e) {log.e("http get throw SocketTimeoutException");} catch (Exception e) {log.e("http get throw Exception");} finally {httpPost.abort();}之前每次代码执⾏到上述代码的第⼆⾏的时候,会等⼀段时间然后会捕获到Exception异常。
2.分析问题当然捕获的Exception这个异常太⼤了我们不便于分析,我们查看⼀下httpClient.execute(HttpUriRequest uri)的⽅法;发下这个⽅法会抛出IOException, ClientProtocolException这两个异常,但是在调⽤⽅法的时候并没有明确捕获他们两个。
Java中实现Http请求并获取响应数据
Java中实现Http请求并获取响应数据⽬录前⾔接⼝说明:获取指定年份或年⽉份的所有节假⽇信息。
默认返回当前年份的所有信息。
跳转链接:以上功能代码仅在使⽤GET请求⽅式时测试通过,POST等其他请求时请⾃⾏尝试。
因未设置请求头时也成功获取了响应数据,所以未在演⽰代码中添加请求头信息,请求失败时可⾃⾏添加请求头信息后重试⽅式⼀:功能实现类.HttpURLConnection请求实现代码:package com.zhiyin.test;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import .HttpURLConnection;import .URL;public class MyTest {public static void main(String[] args) {test();}// HttpURLConnection⽅式public static void test() {String SUBMIT_METHOD_GET = "GET"; // ⼀定要是⼤写,否则请求⽆效String urlStr = "http://timor.tech/api/holiday/year/"; // 请求http地址String param = "2020"; // 请求参数HttpURLConnection connection = null;InputStream is = null;BufferedReader br = null;String result = null; // 返回结果字符串try {// 创建远程url连接对象URL url = new URL(urlStr);// 通过远程url连接对象打开⼀个连接,强转成httpURLConnection类connection = (HttpURLConnection) url.openConnection();// 设置连接⽅式:GETconnection.setRequestMethod(SUBMIT_METHOD_GET);// 设置连接主机服务器的超时时间:15000毫秒connection.setConnectTimeout(15000);// 设置读取远程返回的数据时间:60000毫秒connection.setReadTimeout(60000);// 发送请求connection.connect();// 通过connection连接,请求成功后获取输⼊流if (connection.getResponseCode() == 200) {is = connection.getInputStream();// 封装输⼊流is,并指定字符集br = new BufferedReader(new InputStreamReader(is, "UTF-8"));// 存放数据StringBuffer sbf = new StringBuffer();String temp = null;while ((temp = br.readLine()) != null) {sbf.append(temp);}result = sbf.toString();}} catch (IOException e) {e.printStackTrace();} finally {// 释放资源if (null != br) {try {br.close();} catch (IOException e) {e.printStackTrace();}}if (null != is) {try {is.close();} catch (IOException e) {e.printStackTrace();}}connection.disconnect(); // 关闭远程连接}System.out.println("Successfully:" + result);}}⽅式⼆:功能实现类org.apache.http.client.methods.HttpGet maven项⽬中pom.xml⽂件⾥引⼊依赖:<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency>请求实现代码:package com.zhiyin.test;import org.apache.http.HttpEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import java.io.InputStream;public class MyTest {public static void main(String[] args) {test();}// HttpGet⽅式public static void test() {try {String urlStr = "http://timor.tech/api/holiday/year/"; // 请求http地址String param = "2020"; // 请求参数// 模拟(创建)⼀个浏览器⽤户CloseableHttpClient client = HttpClients.createDefault();HttpGet httpGet = new HttpGet(urlStr + param);// httpclient进⾏连接CloseableHttpResponse response = client.execute(httpGet); // 获取内容HttpEntity entity = response.getEntity();// 将内容转化成IO流InputStream content = entity.getContent();// 输⼊流转换成字符串byte[] byteArr = new byte[content.available()];content.read(byteArr); // 将输⼊流写⼊到字节数组中String result = new String(byteArr);System.out.println("Successfully:" + result);} catch (Exception e) {e.printStackTrace();}}}。
Java 发送https 的post请求方法
Java 发送https 的post请求方法import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import .MalformedURLException; import .URL;import java.security.GeneralSecurityException; import java.security.KeyStore;import .ssl.HostnameVerifier;import .ssl.HttpsURLConnection; import .ssl.KeyManagerFactory; import .ssl.SSLContext;import .ssl.TrustManagerFactory;public class HttpsPost {/*** 获得KeyStore.* @param keyStorePath* 密钥库路径* 密码* @return 密钥库* @throws Exception*/public static KeyStore getKeyStore(String password, String keyStorePath)throws Exception {// 实例化密钥库KeyStore ks = KeyStore.getInstance("JKS");// 获得密钥库文件流FileInputStream is = newFileInputStream(keyStorePath);// 加载密钥库ks.load(is, password.toCharArray());// 关闭密钥库文件流is.close();return ks;}/*** 获得SSLSocketFactory.* 密码* @param keyStorePath* 密钥库路径* @param trustStorePath* 信任库路径* @return SSLSocketFactory* @throws Exception*/public static SSLContext getSSLContext(String password,String keyStorePath, String trustStorePath) throws Exception {// 实例化密钥库KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDe faultAlgorithm());// 获得密钥库KeyStore keyStore = getKeyStore(password, keyStorePath);// 初始化密钥工厂keyManagerFactory.init(keyStore,password.toCharArray());// 实例化信任库TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getD efaultAlgorithm());// 获得信任库KeyStore trustStore = getKeyStore(password, trustStorePath);// 初始化信任库trustManagerFactory.init(trustStore);// 实例化SSL上下文SSLContext ctx =SSLContext.getInstance("TLS");// 初始化SSL上下文ctx.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(), null);// 获得SSLSocketFactoryreturn ctx;}/*** 初始化HttpsURLConnection.* @param password* 密码* @param keyStorePath* 密钥库路径* @param trustStorePath* 信任库路径* @throws Exception*/public static void initHttpsURLConnection(String password,String keyStorePath, String trustStorePath) throws Exception {// 声明SSL上下文SSLContext sslContext = null;// 实例化主机名验证接口HostnameVerifier hnv = new MyHostnameVerifier();try {sslContext = getSSLContext(password, keyStorePath, trustStorePath);} catch (GeneralSecurityException e) {e.printStackTrace();}if (sslContext != null) {HttpsURLConnection.setDefaultSSLSocketFactory(sslCon text.getSocketFactory());}HttpsURLConnection.setDefaultHostnameVerifier(hnv);}/*** 发送请求.* @param httpsUrl* 请求的地址* @param xmlStr* 请求的数据*/public static void post(String httpsUrl, String xmlStr) { HttpsURLConnection urlCon = null;try {urlCon = (HttpsURLConnection) (newURL(httpsUrl)).openConnection();urlCon.setDoInput(true);urlCon.setDoOutput(true);urlCon.setRequestMethod("POST");urlCon.setRequestProperty("Content-Length",String.valueOf(xmlStr.getBytes().length));urlCon.setUseCaches(false);//设置为gbk可以解决服务器接收时读取的数据中文乱码问题urlCon.getOutputStream().write(xmlStr.getBytes("gbk"));urlCon.getOutputStream().flush();urlCon.getOutputStream().close();BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));String line;while ((line = in.readLine()) != null) {System.out.println(line);}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}/*** 测试方法.* @param args* @throws Exception*/public static void main(String[] args) throws Exception {// 密码String password = "123456";// 密钥库String keyStorePath = "tomcat.keystore";// 信任库String trustStorePath = "tomcat.keystore";// 本地起的https服务String httpsUrl ="https://localhost:8443/service/httpsPost";// 传输文本String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><fruitShop><fruits><fr uit><kind>萝卜</kind></fruit><fruit><kind>菠萝</kind></fruit></fruits></fruitShop>";HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);// 发起请求HttpsPost.post(httpsUrl, xmlStr);}} [java] viewplaincopyimport .ssl.HostnameVerifier;import .ssl.SSLSession;/*** 实现用于主机名验证的基接口。
java爬虫抓取网页数据教程
java爬虫抓取网页数据教程数据是科研活动重要的基础,而爬虫是获取数据一个比较常见的方法,爬虫的基本原理很简单,就是利用程序访问互联网,然后将数据保存到本地中。
我们都知道,互联网提供的服务大多数是以网站的形式提供的。
我们需要的数据一般都是从网站中获取的,如电商网站商品信息、商品的评论、微博的信息等。
爬虫和我们手动将看到的数据复制粘贴下来是类似的,只是获取大量的数据靠人工显然不太可能。
因此,需要我们使用工具来帮助获取知识。
使用程序编写爬虫就是使用程序编写一些网络访问的规则,将我们的目标数据保存下来。
Java作为爬虫语言的一种,下面为大家介绍java爬虫抓取网页数据教程。
1、使用bbbClient简单抓取网页首先,假设我们需要爬取数据学习网站上第一页的博客(bbb://aaadatalearneraaa/blog)。
首先,我们需要使用导入bbbClient 4.5.3这个包(这是目前最新的包,你可以根据需要使用其他的版本)。
Java本身提供了关于网络访问的包,在中,然后它不够强大。
于是Apache基金会发布了开源的bbb请求的包,即bbbClient,这个包提供了非常多的网络访问的功能。
在这里,我们也是使用这个包来编写爬虫。
好了,使用pom.xml下载完这个包之后我们就可以开始编写我们的第一个爬虫例子了。
其代码如下(注意,我们的程序是建立在test包下面的,因此,需要在这个包下才能运行):package test;import org.apache.bbb.bbbEntity;importorg.apache.bbb.client.methods.CloseablebbbResponse;import org.apache.bbb.client.methods.bbbGet;importorg.apache.bbb.impl.client.CloseablebbbClient;importorg.apache.bbb.impl.client.bbbClients;importorg.apache.bbb.util.EntityUtils;import java.io.IOException;/*** 第一个爬虫测试* Created by DuFei on 2017/7/27.*/public class FirstTest {public static void main(String[] args) {//建立一个新的请求客户端CloseablebbbClient bbbClient =bbbClients.createDefault();//使用bbbGet方式请求网址bbbGet bbbGet = new bbbGet("bbb://aaadatalearneraaa/blog");//获取网址的返回结果CloseablebbbResponse response = null;try {response = bbbClient.execute(bbbGet);} catch (IOException e) {e.printStackTrace();}//获取返回结果中的实体bbbEntity entity = response.getEntity();//将返回的实体输出try {System.out.println(EntityUtils.toString(entity));EntityUtils.consume(entity);} catch (IOException e) {e.printStackTrace();}}}如上面的代码所示,爬虫的第一步需要构建一个客户端,即请求端,我们这里使用CloseablebbbClient作为我们的请求端,然后确定使用哪种方式请求什么网址,再然后使用bbbResponse获取请求的位置对应的结果即可。
JavaHttpURLConnection抓取网页内容解析gzip格式输入流数据并转换为S。。。
JavaHttpURLConnection抓取⽹页内容解析gzip格式输⼊流数据并转换为S。
最近GFW为了刷存在感,搞得⼤家是头晕眼花,修改hosts ⼏乎成了每⽇必备⼯作。
索性写了⼀个⼩程序,给办公室的同事们分享,其中有个内容就是抓取⽹络上的hosts,废了⼀些周折。
我是在⼀个博客上抓取的。
但是这位朋友的博客应该是在做防盗链,但他的⽅式⽐较简单就是5位数的⼀个整形随机数。
这⾥折腾⼀下就ok了。
要命的是他这个链接的流类型居然是gzip。
这个郁闷好久,⼀直以为是编码格式导致解析不出来结果,后来发现是gzip搞的。
主要的⼀段代码做个记录吧。
1/**2 * ⽹络⼯具类⽤于抓取上的hosts数据3 *4 * @author tone5*/6public class NetUtil {78private final static String ENCODING = "UTF-8";9private final static String GZIPCODING = "gzip";10private final static String HOST = "/pub/hosts.php";11private final static String COOKIE = "hostspasscode=%s; Hm_lvt_e26a7cd6079c926259ded8f19369bf0b=1421846509,1421846927,1421847015,1421849633; Hm_lpvt_e26a7cd6079c926259ded8f19369bf0b=1421849633" 12private final static String OFF = "off";13private final static String ON = "on";14private final static int RANDOM = 100000;15private static String hostspasscode = null;16private static NetUtil instance;1718public static NetUtil getInstance() {19if (instance == null) {20 instance = new NetUtil();21 }22return instance;23 }2425private NetUtil() {26 hostspasscode = createRandomCookies();27 }2829/**30 * 获取html内容31 *32 * @param gs33 * @param wk34 * @param twttr35 * @param fb36 * @param flkr37 * @param dpbx38 * @param odrvB39 * @param yt40 * @param nohl41 * @return42*/43public String getHtmlInfo(boolean gs, boolean wk, boolean twttr, boolean fb,44boolean flkr, boolean dpbx, boolean odrv,45boolean yt, boolean nohl) throws Exception {46 HttpURLConnection conn = null;4748 String result = "";4950//String cookie = "hostspasscode="+hostspasscode+"; Hm_lvt_e26a7cd6079c926259ded8f19369bf0b=1421846509,1421846927,1421847015,1421849633; Hm_lpvt_e26a7cd6079c926259ded8f19369bf0b=1421849633";51 String cookie = String.format(COOKIE, hostspasscode);5253//URL url = new URL("/pub/hosts.php?passcode=13008&gs=on&wk=on&twttr=on&fb=on&flkr=on&dpbx=on&odrv=on&yt=on&nolh=on");54 URL url = new URL(createUrl(hostspasscode, gs, wk, twttr, fb, flkr, dpbx, odrv, yt, nohl));55//System.out.println(cookie);56// System.out.println(url.toString());5758 conn = (HttpURLConnection) url.openConnection();5960 conn.setConnectTimeout(5 * 1000);61 conn.setDoOutput(true);62//get⽅式提交63 conn.setRequestMethod("GET");64//凭借请求头⽂件65 conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");66 conn.setRequestProperty("Accept-Encoding", "gzip, deflate");67 conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");68 conn.setRequestProperty("Connection", "keep-alive");69 conn.setRequestProperty("Cookie", cookie);70 conn.setRequestProperty("Host", "");71 conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:35.0) Gecko/20100101 Firefox/35.0");7273// conn.setRequestProperty("Referer", "/pub/gethosts.php");74// conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");7576 conn.connect();7778 String encoding = conn.getContentEncoding();7980 result = readStream(conn.getInputStream(), encoding);81//测试进度条显⽰82// result = readStream(new FileInputStream(new File("/home/tone/Resident.Evil.Damnation.2012.1080p.BluRay.x264.DTS-WiKi.mkv")), "11");8384 conn.disconnect();85if (nohl) {86 result=getLocalHost()+result;87 }8889return result;90 }9192/**93 * 读取将InputStream中的字节读以字符的形式取到字符串中,如果encoding是gzip,那么需要先有GZIPInputStream进⾏封装95 * @param inputStream InputStream字节流96 * @param encoding 编码格式97 * @return String类型的形式98 * @throws IOException IO异常99*/100private String readStream(InputStream inputStream, String encoding) throws Exception {101 StringBuffer buffer = new StringBuffer();102 ProgressMonitorInputStream pmis = null;103104 InputStreamReader inputStreamReader = null;105 GZIPInputStream gZIPInputStream = null;106if (GZIPCODING.equals(encoding)) {107 gZIPInputStream = new GZIPInputStream(inputStream);108 inputStreamReader = new InputStreamReader(ProgressUtil.getMonitorInputStream(gZIPInputStream, "获取⽹络数据"), ENCODING); 109110 } else {111112 inputStreamReader = new InputStreamReader(ProgressUtil.getMonitorInputStream(inputStream, "获取⽹络数据"), ENCODING); 113 }114115116char[] c = new char[1024];117118int lenI;119while ((lenI = inputStreamReader.read(c)) != -1) {120121 buffer.append(new String(c, 0, lenI));122123 }124if (inputStream != null) {125 inputStream.close();126 }127if (gZIPInputStream != null) {128 gZIPInputStream.close();129 }130if (pmis!=null) {131 gZIPInputStream.close();132 }133134135return buffer.toString();136137138 }139140/**141 * ⽣成随机Cookies数组142 *143 * @return五位随机数字144*/145private String createRandomCookies() {146147return String.valueOf(Math.random() * RANDOM).substring(0, 5);148149 }150151/**152 * ⽣成链接字符串153 *154 * @param hostspasscode155 * @param gs156 * @param wk157 * @param twttr158 * @param fb159 * @param flkr160 * @param dpbx161 * @param odrvB162 * @param yt163 * @param nohl164 * @return165*/166private String createUrl(String hostspasscode, boolean gs, boolean wk, boolean twttr, boolean fb,167boolean flkr, boolean dpbx, boolean odrv,168boolean yt, boolean nohl) {169 StringBuffer buffer = new StringBuffer();170 buffer.append(HOST);171 buffer.append("?passcode=" + hostspasscode);172if (gs) {173 buffer.append("&gs=" + ON);174 } else {175 buffer.append("&gs=" + OFF);176 }177if (wk) {178 buffer.append("&wk=" + ON);179 } else {180 buffer.append("&wk=" + OFF);181 }182if (twttr) {183 buffer.append("&twttr=" + ON);184 } else {185 buffer.append("&twttr=" + OFF);186 }187if (fb) {188 buffer.append("&fb=" + ON);189 } else {190 buffer.append("&fb=" + OFF);191 }192if (flkr) {193 buffer.append("&flkr=" + ON);194 } else {195 buffer.append("&flkr=" + OFF);196 }197if (dpbx) {198 buffer.append("&dpbx=" + ON);199 } else {200 buffer.append("&dpbx=" + OFF);201 }202if (odrv) {203 buffer.append("&odrv=" + ON);204 } else {205 buffer.append("&odrv=" + OFF);207if (yt) {208 buffer.append("&yt=" + ON);209 } else {210 buffer.append("&yt=" + OFF);211 }212if (nohl) {213 buffer.append("&nohl=" + ON);214 } else {215 buffer.append("&nohl=" + OFF);216 }217return buffer.toString();218 }219220private String getLocalHost() throws Exception {221222 StringBuffer buffer=new StringBuffer();223 String hostName=OSUtil.getInstance().getLocalhostName(); 224 buffer.append("#LOCALHOST begin"+"\n");225 buffer.append("127.0.0.1\tlocalhost"+"\n");226if (hostName!=null&&!"".equals(hostName)) {227 buffer.append("127.0.1.1\t"+hostName+"\n");228 }229230 buffer.append("#LOCALHOST end"+"\n");231return buffer.toString();232233234235 }236237 }。
java获取https网站证书,附带调用https:webservice接口
java获取https⽹站证书,附带调⽤https:webservice接⼝⼀、java 获取https⽹站证书: 1、创建⼀个java⼯程,新建InstallCert类,将以下代码复制进去package com;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.security.KeyStore;import java.security.MessageDigest;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import .ssl.SSLContext;import .ssl.SSLException;import .ssl.SSLSocket;import .ssl.SSLSocketFactory;import .ssl.TrustManager;import .ssl.TrustManagerFactory;import .ssl.X509TrustManager;/*** 从⽹站获取java所需的证书,调⽤时传⼊域名。
*/public class InstallCert {public static void main(String[] args) throws Exception {String host;int port;char[] passphrase;if ((args.length == 1) || (args.length == 2)) {String[] c = args[0].split(":");host = c[0];port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);String p = (args.length == 1) ? "changeit" : args[1];passphrase = p.toCharArray();} else {System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");return;}File file = new File("jssecacerts");if (file.isFile() == false) {char SEP = File.separatorChar;File dir = new File(System.getProperty("java.home") + SEP+ "lib" + SEP + "security");file = new File(dir, "jssecacerts");if (file.isFile() == false) {file = new File(dir, "cacerts");}}System.out.println("Loading KeyStore " + file + "...");InputStream in = new FileInputStream(file);KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());ks.load(in, passphrase);in.close();SSLContext context = SSLContext.getInstance("TLS");TrustManagerFactory tmf =TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());tmf.init(ks);X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);context.init(null, new TrustManager[] {tm}, null);SSLSocketFactory factory = context.getSocketFactory();System.out.println("Opening connection to " + host + ":" + port + "...");SSLSocket socket = (SSLSocket)factory.createSocket(host, port);socket.setSoTimeout(10000);try {System.out.println("Starting SSL handshake...");socket.startHandshake();socket.close();System.out.println();System.out.println("No errors, certificate is already trusted");} catch (SSLException e) {System.out.println();e.printStackTrace(System.out);}X509Certificate[] chain = tm.chain;if (chain == null) {System.out.println("Could not obtain server certificate chain");return;}BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));System.out.println();System.out.println("Server sent " + chain.length + " certificate(s):");System.out.println();MessageDigest sha1 = MessageDigest.getInstance("SHA1");MessageDigest md5 = MessageDigest.getInstance("MD5");for (int i = 0; i < chain.length; i++) {X509Certificate cert = chain[i];System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());System.out.println(" Issuer " + cert.getIssuerDN());sha1.update(cert.getEncoded());System.out.println(" sha1 " + toHexString(sha1.digest()));md5.update(cert.getEncoded());System.out.println(" md5 " + toHexString(md5.digest()));System.out.println();}System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");String line = reader.readLine().trim();int k;try {k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;} catch (NumberFormatException e) {System.out.println("KeyStore not changed");return;}X509Certificate cert = chain[k];String alias = host + "-" + (k + 1);ks.setCertificateEntry(alias, cert);OutputStream out = new FileOutputStream("jssecacerts");ks.store(out, passphrase);out.close();System.out.println();System.out.println(cert);System.out.println();System.out.println("Added certificate to keystore 'jssecacerts' using alias '"+ alias + "'");}private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();private static String toHexString(byte[] bytes) {StringBuilder sb = new StringBuilder(bytes.length * 3);for (int b : bytes) {b &= 0xff;sb.append(HEXDIGITS[b >> 4]);sb.append(HEXDIGITS[b & 15]);sb.append(' ');}return sb.toString();}private static class SavingTrustManager implements X509TrustManager {private final X509TrustManager tm;private X509Certificate[] chain;SavingTrustManager(X509TrustManager tm) {this.tm = tm;}public X509Certificate[] getAcceptedIssuers() {throw new UnsupportedOperationException();}public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {throw new UnsupportedOperationException();}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {this.chain = chain;tm.checkServerTrusted(chain, authType);}}}InstallCert.java2、eclipse 传⼊参数(需要获取证书的域名,例:)运⾏main⽅法:注:这⾥注意更改参数的类,不要弄错了。
JAVA抓取网站数据
JAVA抓取网站数据JAVA抓取网站数据00可以使用抓取的类库包括JDK自带URL或第三方的HttpClient,这里使用URL基础类库访问网络。
其实,用JDK自带的URL模拟网站请求,并返回数据是个模板式的过程,只可能有时候碰到多重跳转,或重定向而采取多个模板式过程而已。
一般流程类似:1将要模拟的请求地址传递给URL2通过URL获得一个连接对象,URLConnection或将其转化为子类HttpURLConnection我常用HttpURLConnection,有时候死活连不上可以尝试切换使用,呵呵。
3通过setRequestProperty函数来设置请求参数,请求方式,具体设置哪些参数对应网站有所不同。
4通过连接对象的函数来设置:诸如禁止自动跳转重定向,超时的时间,输入输出设定等。
5调用connect(),开始连接地址。
5如果请求为get,附带参数;或post,附带表单信息,则通过getOutputStream函数传递,这个函数自带connect()过程,所以第5步有这方法存在则省略。
注:output必须在input之前执行,否则抛异常。
6 通过getResponseCode得到连接并发送参数后返回的状态码:可能为跳转地址,重定向地址,也可能为直接返回数据。
注:在第3或4步中设置setInstanceFollowRedirects(false);便于分析每次请求后的流程,是得到数据还是跳转了地址等等。
200成功连接服务,但不表示满足网站的业务需求,比如登录成功等。
301 302跳转或重定向可以通过getHeaderField("location");得到接下来转向地址500 与服务器连接失败,首先检测User-Agent请求头模拟信息是否准确。
7 通过getInputStream()得到请求成功后的信息数据流。
8 通过IO可以尝试测试返回的数据信息,如果是压缩包或者文件可以通过IO来下载保存9第一次请求不需要Cookie信息,但是如果需要接下来的请求,可能会涉及需要登录以后才可以操作的流程,所以需要把第一次生成的session传递下去。
Java的网络爬虫使用Java抓取互联网数据
Java的网络爬虫使用Java抓取互联网数据随着互联网的迅猛发展和信息量的剧增,人们对于获取互联网数据的需求也越来越高。
为了满足这一需求,网络爬虫应运而生。
网络爬虫是一种自动化程序,能够模拟人的行为,在互联网上按照一定的规则获取所需的数据。
Java作为一种高级编程语言,在网络爬虫的开发中得到了广泛应用。
Java的网络爬虫主要通过HTTP协议来实现数据的抓取。
HTTP是一种无状态的协议,通过发送请求(Request)和接收响应(Response)来进行通信。
Java提供了丰富的网络编程库,开发者可以利用这些库来构建网络爬虫。
在使用Java开发网络爬虫时,首先需要确定所需抓取的目标网站。
然后,需要了解该网站的页面结构和数据格式,以便编写相应的抓取程序。
一般来说,网络爬虫的抓取过程主要包括以下几个步骤:1. 发送HTTP请求:Java提供了HttpURLConnection和HttpClient等类,可以用来发送HTTP请求。
我们可以通过这些类来模拟浏览器发送请求,获取网页内容。
2. 解析HTML:抓取到的网页内容一般是HTML格式的,需要使用HTML解析库来提取所需的数据。
Java中常用的HTML解析库有Jsoup和HtmlUnit等,它们提供了丰富的API,可以方便地解析和操作HTML文档。
3. 数据处理和存储:通过解析HTML文档,我们可以获取到所需的数据。
接下来,需要对这些数据进行处理和存储。
Java提供了各种数据处理和存储的工具和框架,例如数据库操作工具JDBC、数据分析框架Hadoop等,可以根据实际需求选择合适的工具和框架。
4. 遵守规则和道德准则:在进行网络爬取时,需要遵守一些规则和道德准则。
首先,需要尊重网站的Robots协议,遵守网站的访问频率限制;其次,需要尊重网站的版权和隐私规定,不得将抓取到的数据用于非法或侵犯他人利益的用途。
除了以上基本步骤,Java的网络爬虫还可以通过多线程、代理IP和验证码识别等技术来提高抓取效率和解决一些难题。
java发https_使用java发送https的请求详解
java发https_使⽤java发送https的请求详解import java.io.BufferedReader;import java.io.InputStreamReader;import .URL;import java.security.cert.CertificateException;import java.util.Map;import .ssl.HostnameVerifier;import .ssl.HttpsURLConnection;import .ssl.SSLContext;import .ssl.SSLSession;import .ssl.TrustManager;import .ssl.X509TrustManager;import java.security.cert.X509Certificate;public class HttpsGetData {private static class TrustAnyTrustManager implements X509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[] {};}}private static class TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify(String hostname, SSLSession session) {return true;}}String _url="";Map _params;public HttpsGetData(String url,Map keyValueParams){this._url=url;this._params=keyValueParams;}public String Do() throws Exception{String result = "";BufferedReader in = null;try {String urlStr = this._url + "&" + getParamStr();System.out.println("GET请求的URL为:"+urlStr);SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());URL realUrl = new URL(urlStr);// 打开和URL之间的连接HttpsURLConnection connection = (HttpsURLConnection) realUrl.openConnection();//设置https相关属性connection.setSSLSocketFactory(sc.getSocketFactory());connection.setHostnameVerifier(new TrustAnyHostnameVerifier());connection.setDoOutput(true);// 设置通⽤的请求属性connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");// 建⽴实际的连接connection.connect();// 定义 BufferedReader输⼊流来读取URL的响应in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8")); String line;while ((line = in.readLine()) != null) {result += line;}System.out.println("获取的结果为:"+result);} catch (Exception e) {System.out.println("发送GET请求出现异常!" + e);//e.printStackTrace();throw e;}// 使⽤finally块来关闭输⼊流finally {try {if (in != null) {in.close();}} catch (Exception e2) {//e2.printStackTrace();throw e2;}}return result;}private String getParamStr(){String paramStr="";// 获取所有响应头字段Map params = this._params;// 获取参数列表组成参数字符串for (String key : params.keySet()) {paramStr+=key+"="+params.get(key)+"&";}//去除最后⼀个"&"paramStr=paramStr.substring(0, paramStr.length()-1); return paramStr;}}。
Java发送https请求代码实例
Java发送https请求代码实例1、前⽂:通过webService发送https请求,有两种版本,⼀种是携带证书验证(⽐较⿇烦),另外⼀种就是直接忽略证书,本⽂提供的就是第⼆种(本⼈已测试过)2、最简易代码:import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.Reader;import .MalformedURLException;import .URL;import java.text.SimpleDateFormat;import .ssl.HostnameVerifier;import .ssl.HttpsURLConnection;import .ssl.SSLSession;@SuppressWarnings("all")public class TestAPI_https {public static void main(String args[]) throws Exception {new TestAPI_https().TestRiQingAPI_SaleOrder();}public static void TestRiQingAPI_SaleOrder() throws Exception {String postData = getJson();//String url = "https://*****";String url = "https://*****";HttpsURLConnection conn = null;OutputStream out = null;String rsp = null;byte[] byteArray = postData.getBytes("utf-8");try {URL uri = new URL(url);conn = (HttpsURLConnection) uri.openConnection();//忽略证书验证--Beginconn.setHostnameVerifier(new TrustAnyHostnameVerifier());//忽略证书验证--Endconn.setRequestMethod("POST");conn.setDoInput(true);conn.setDoOutput(true);conn.setRequestProperty("Host", uri.getHost());conn.setRequestProperty("Content-Type", "application/json");out = conn.getOutputStream();out.write(byteArray);out.close();if(conn.getResponseCode()==200) {rsp = getStreamAsString(conn.getInputStream(), "utf-8");}else {rsp = getStreamAsString(conn.getErrorStream(), "utf-8");}System.out.println(rsp);} catch (Exception e) {if(null!=out)out.close();e.printStackTrace();}}/*** getJson**/private static String getJson() {return "{" + "\"name\"" + ":" + "\"robo_blogs_zh123\"" + "}";}private static String getStreamAsString(InputStream stream, String charset) throws IOException { try {Reader reader = new InputStreamReader(stream, charset);StringBuilder response = new StringBuilder();final char[] buff = new char[1024];int read = 0;while ((read = reader.read(buff)) > 0) {response.append(buff, 0, read);}return response.toString();} finally {if (stream != null) {stream.close();}}}}//定制Verifierclass TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify(String hostname, SSLSession session) {return true;}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
java发起HTTPS请求
摘要JSSE是一个SSL和TLS的纯Java实现,通过JSSE可以很容易地编程实现对HTTP S 站点的访问。
但是,如果该站点的证书未经权威机构的验证,JSSE将拒绝信任该证书从而不能访问HTT PS站点。
本文在简要介绍JSSE的基础上提出了两种解决该问题的方法。
引言过去的十几年,网络上已经积累了大量的Web应用。
如今,无论是整合原有的Web应用系统,还是进行新的Web开发,都要求通过编程来访问某些Web页面。
传统的方法是使用Soc ket接口,但现在很多开发平台或工具如.NET、Java或P HP 等都提供了简单的Web访问接口,使用这些接口很容易编程实现与We b应用系统的交互访问,即使要访问那些采用了H TTPS而不是HTT P的Web应用系统。
HTTPS,即安全的超文本传输协议,采用了SSL技术,被广泛使用以保证Web 应用系统的安全性。
访问Web应用的编程接口大多封装了SSL,使得访问HT TPS 和访问HTTP一样简单。
但是很多中、小型应用系统或基于局域网、校园网的应用系统所使用的证书并不是由权威的认证机构发行或者被其验证,直接使用这些编程接口将不能访问H TTPS。
本文将在简要介绍JSS E的基础上,详细描述使用JSSE访问HTTP S的方法,主要说明了如何访问带有未经验证证书的HTT PS站点。
JSSE简介Java安全套接扩展(Java Secure Socket Extens ion, JSSE)是实现Int ernet 安全通信的一系列包的集合。
它是一个SS L和TLS的纯Jav a实现,可以透明地提供数据加密、服务器认证、信息完整性等功能,可以使我们像使用普通的套接字一样使用JSS E建立的安全套接字。
关于JAVA发送Https请求(HttpsURLConnection和HttpURLCon。。。
关于JAVA发送Https请求(HttpsURLConnection和HttpURLCon。
关于JAVA发送Https请求(HttpsURLConnection和HttpURLConnection)【转】https协议对于开发者⽽⾔其实只是多了⼀步证书验证的过程。
这个证书正常情况下被jdk/jre/security/cacerts所管理。
⾥⾯证书包含两种情况:1、机构所颁发的被认证的证书,这种证书的⽹站在浏览器访问时https头显⽰为绿⾊如百度2、个⼈所设定的证书,这种证书的⽹站在浏览器⾥https头显⽰为红⾊×,且需要点击信任该⽹站才能继续访问。
⽽点击信任这⼀步的操作就是我们在java代码访问https⽹站时区别于http请求需要做的事情。
所以JAVA发送Https请求有两种情况,三种解决办法:第⼀种情况:Https⽹站的证书为机构所颁发的被认证的证书,这种情况下和http请求⼀模⼀样,⽆需做任何改变,⽤HttpsURLConnection 或者HttpURLConnection都可以[java]1. public static void main(String[] args) throws Exception{2. URL serverUrl = new URL("https://xxxx");3. HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();4. conn.setRequestMethod("GET");5. conn.setRequestProperty("Content-type", "application/json");6. //必须设置false,否则会⾃动redirect到重定向后的地址7. conn.setInstanceFollowRedirects(false);8. conn.connect();9. String result = getReturn(conn);10. }11.12. /*请求url获取返回的内容*/13. public static String getReturn(HttpURLConnection connection) throws IOException{14. StringBuffer buffer = new StringBuffer();15. //将返回的输⼊流转换成字符串16. try(InputStream inputStream = connection.getInputStream();17. InputStreamReader inputStreamReader = new InputStreamReader(inputStream, ConstantInfo.CHARSET);18. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);){19. String str = null;20. while ((str = bufferedReader.readLine()) != null) {21. buffer.append(str);22. }23. String result = buffer.toString();24. return result;25. }26. }第⼆种情况:个⼈所设定的证书,这种证书默认不被信任,需要我们⾃⼰选择信任,信任的办法有两种:A、将证书导⼊java的运⾏环境中从该⽹站下载或者从⽹站开发者出获取证书cacert.crt运⾏命令将证书导⼊java运⾏环境:keytool -import -keystore %JAVA_HOME%\jre\lib\security\cacerts -file cacert.crt -alias xxx 完成。
Java调用HttpHttps接口(4)--HttpClient调用HttpHttps接口
Java调⽤HttpHttps接⼝(4)--HttpClient调⽤HttpHttps接⼝HttpClient是Apache HttpComponents项⽬下的⼀个组件,是Commons-HttpClient的升级版,两者api调⽤写法也很类似。
⽂中所使⽤到的软件版本:Java 1.8.0_191、HttpClient 4.5.10。
1、服务端参见2、调⽤Http接⼝2.1、GET请求public static void get() {String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李⽩";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpGet get = new HttpGet(requestPath);CloseableHttpResponse response = httpClient.execute(get);System.out.println("GET返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Get(requestPath).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("GET fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.2、POST请求(发送键值对数据)public static void post() {String requestPath = "http://localhost:8080/demo/httptest/getUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);List<NameValuePair> list = new ArrayList<NameValuePair>();list.add(new BasicNameValuePair("userId", "1000"));list.add(new BasicNameValuePair("userName", "李⽩"));post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyForm(Form.form().add("userId", "1000").add("userName", "李⽩").build(), Charset.forName("utf-8")).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.3、POST请求(发送JSON数据)public static void post2() {String requestPath = "http://localhost:8080/demo/httptest/addUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);post.setHeader("Content-type", "application/json");String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";post.setEntity(new StringEntity(param, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST json返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).addHeader("Content-type", "application/json").bodyString(param, ContentType.APPLICATION_JSON).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST json fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.4、上传⽂件public static void upload() {String requestPath = "http://localhost:8080/demo/httptest/upload";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");post.setEntity(new InputStreamEntity(fileInputStream));CloseableHttpResponse response = httpClient.execute(post);System.out.println("upload返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyStream(new FileInputStream("d:/a.jpg")).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("upload fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.5、上传⽂件及发送键值对数据public static void multi() {String requestPath = "http://localhost:8080/demo/httptest/multi";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileBody file = new FileBody(new File("d:/a.jpg"));HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build();post.setEntity(requestEntity);CloseableHttpResponse response = httpClient.execute(post);System.out.println("multi返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).body(MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build()).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("multi fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}2.6、完整例⼦package com.inspur.demo.http.client;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpEntity;import ValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.fluent.Form;import org.apache.http.client.fluent.Request;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.ContentType;import org.apache.http.entity.InputStreamEntity;import org.apache.http.entity.StringEntity;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;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;/*** 通过HttpClient调⽤Http接⼝*/public class HttpClientCase {/*** GET请求*/public static void get() {String requestPath = "http://localhost:8080/demo/httptest/getUser?userId=1000&userName=李⽩";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpGet get = new HttpGet(requestPath);CloseableHttpResponse response = httpClient.execute(get);System.out.println("GET返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("GET返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Get(requestPath).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("GET fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** POST请求(发送键值对数据)*/public static void post() {String requestPath = "http://localhost:8080/demo/httptest/getUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);List<NameValuePair> list = new ArrayList<NameValuePair>();list.add(new BasicNameValuePair("userId", "1000"));list.add(new BasicNameValuePair("userName", "李⽩"));post.setEntity(new UrlEncodedFormEntity(list, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyForm(Form.form().add("userId", "1000").add("userName", "李⽩").build(), Charset.forName("utf-8")) .execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** POST请求(发送json数据)*/public static void post2() {String requestPath = "http://localhost:8080/demo/httptest/addUser";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);post.setHeader("Content-type", "application/json");String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";post.setEntity(new StringEntity(param, "utf-8"));CloseableHttpResponse response = httpClient.execute(post);System.out.println("POST json返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("POST josn返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).addHeader("Content-type", "application/json").bodyString(param, ContentType.APPLICATION_JSON).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("POST json fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** 上传⽂件*/public static void upload() {String requestPath = "http://localhost:8080/demo/httptest/upload";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");post.setEntity(new InputStreamEntity(fileInputStream));CloseableHttpResponse response = httpClient.execute(post);System.out.println("upload返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("upload返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).bodyStream(new FileInputStream("d:/a.jpg")).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("upload fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}/*** 上传⽂件及发送键值对数据*/public static void multi() {String requestPath = "http://localhost:8080/demo/httptest/multi";CloseableHttpClient httpClient = HttpClients.createDefault();try {HttpPost post = new HttpPost(requestPath);FileBody file = new FileBody(new File("d:/a.jpg"));HttpEntity requestEntity = MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .build();post.setEntity(requestEntity);CloseableHttpResponse response = httpClient.execute(post);System.out.println("multi返回状态:" + response.getStatusLine());HttpEntity responseEntity = response.getEntity();System.out.println("multi返回结果:" + EntityUtils.toString(responseEntity));//流畅api调⽤String result = Request.Post(requestPath).body(MultipartEntityBuilder.create().addPart("file", file).addPart("param1", new StringBody("参数1", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))) .addPart("param2", new StringBody("参数2", ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), "utf-8"))).build()).execute().returnContent().asString(Charset.forName("utf-8"));System.out.println("multi fluent返回结果:" + result);} catch (Exception e) {e.printStackTrace();} finally {close(httpClient);}}private static void close(CloseableHttpClient httpClient) {try {if (httpClient != null) {httpClient.close();}} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) {get();post();post2();upload();multi();}}View Code3、调⽤Https接⼝与调⽤Http接⼝不⼀样的部分主要在设置ssl部分,其ssl的设置与HttpsURLConnection很相似(参见);下⾯⽤GET请求来演⽰ssl的设置,其他调⽤⽅式类似。
Java 发送https 的post请求方法
Java 发送https 的post请求方法import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import .MalformedURLException; import .URL;import java.security.GeneralSecurityException; import java.security.KeyStore;import .ssl.HostnameVerifier;import .ssl.HttpsURLConnection; import .ssl.KeyManagerFactory; import .ssl.SSLContext;import .ssl.TrustManagerFactory;public class HttpsPost {/*** 获得KeyStore.* @param keyStorePath* 密钥库路径* 密码* @return 密钥库* @throws Exception*/public static KeyStore getKeyStore(String password, String keyStorePath)throws Exception {// 实例化密钥库KeyStore ks = KeyStore.getInstance("JKS");// 获得密钥库文件流FileInputStream is = newFileInputStream(keyStorePath);// 加载密钥库ks.load(is, password.toCharArray());// 关闭密钥库文件流is.close();return ks;}/*** 获得SSLSocketFactory.* 密码* @param keyStorePath* 密钥库路径* @param trustStorePath* 信任库路径* @return SSLSocketFactory* @throws Exception*/public static SSLContext getSSLContext(String password,String keyStorePath, String trustStorePath) throws Exception {// 实例化密钥库KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDe faultAlgorithm());// 获得密钥库KeyStore keyStore = getKeyStore(password, keyStorePath);// 初始化密钥工厂keyManagerFactory.init(keyStore,password.toCharArray());// 实例化信任库TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getD efaultAlgorithm());// 获得信任库KeyStore trustStore = getKeyStore(password, trustStorePath);// 初始化信任库trustManagerFactory.init(trustStore);// 实例化SSL上下文SSLContext ctx =SSLContext.getInstance("TLS");// 初始化SSL上下文ctx.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(), null);// 获得SSLSocketFactoryreturn ctx;}/*** 初始化HttpsURLConnection.* @param password* 密码* @param keyStorePath* 密钥库路径* @param trustStorePath* 信任库路径* @throws Exception*/public static void initHttpsURLConnection(String password,String keyStorePath, String trustStorePath) throws Exception {// 声明SSL上下文SSLContext sslContext = null;// 实例化主机名验证接口HostnameVerifier hnv = new MyHostnameVerifier();try {sslContext = getSSLContext(password, keyStorePath, trustStorePath);} catch (GeneralSecurityException e) {e.printStackTrace();}if (sslContext != null) {HttpsURLConnection.setDefaultSSLSocketFactory(sslCon text.getSocketFactory());}HttpsURLConnection.setDefaultHostnameVerifier(hnv);}/*** 发送请求.* @param httpsUrl* 请求的地址* @param xmlStr* 请求的数据*/public static void post(String httpsUrl, String xmlStr) { HttpsURLConnection urlCon = null;try {urlCon = (HttpsURLConnection) (newURL(httpsUrl)).openConnection();urlCon.setDoInput(true);urlCon.setDoOutput(true);urlCon.setRequestMethod("POST");urlCon.setRequestProperty("Content-Length",String.valueOf(xmlStr.getBytes().length));urlCon.setUseCaches(false);//设置为gbk可以解决服务器接收时读取的数据中文乱码问题urlCon.getOutputStream().write(xmlStr.getBytes("gbk"));urlCon.getOutputStream().flush();urlCon.getOutputStream().close();BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));String line;while ((line = in.readLine()) != null) {System.out.println(line);}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}/*** 测试方法.* @param args* @throws Exception*/public static void main(String[] args) throws Exception {// 密码String password = "123456";// 密钥库String keyStorePath = "tomcat.keystore";// 信任库String trustStorePath = "tomcat.keystore";// 本地起的https服务String httpsUrl ="https://localhost:8443/service/httpsPost";// 传输文本String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><fruitShop><fruits><fr uit><kind>萝卜</kind></fruit><fruit><kind>菠萝</kind></fruit></fruits></fruitShop>";HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);// 发起请求HttpsPost.post(httpsUrl, xmlStr);}} [java] viewplaincopyimport .ssl.HostnameVerifier;import .ssl.SSLSession;/*** 实现用于主机名验证的基接口。
java实现反向代理返回页面内容的方法
java实现反向代理返回页面内容的方法要实现反向代理并返回页面内容,你可以使用Java的Servlet技术。
以下是一个简单的示例,它创建了一个Servlet,该Servlet接收客户端的请求,然后转发到目标服务器,并将目标服务器的响应返回给客户端。
javaimport java io ;import javax servlet ;import javax servlet http ;public class ProxyServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 获取目标服务器的URLString targetUrl = example; // 替换为你的目标服务器地址HttpURLConnection connection = (HttpURLConnection) newURL(targetUrl) openConnection();connection setRequestMethod("GET");connection setRequestProperty("User-Agent", requestgetHeader("User-Agent"));// 将请求发送到目标服务器int responseCode = connection getResponseCode();InputStream inputStream;if (responseCode == HttpURLConnection HTTP_OK) { // 200 OKinputStream = connection getInputStream();} else {inputStream = connection getErrorStream();}// 将目标服务器的响应返回给客户端BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));StringBuilder responseString = new StringBuilder();String line;while ((line = reader readLine()) != null) {responseString append(line);}response getWriter() write(responseString toString());}}这个示例使用了Java的URLConnection类来发送HTTP请求并接收响应。
jsoup中connection的execute方法 -回复
jsoup中connection的execute方法-回复关于jsoup中connection的execute方法JSoup是一个用于处理HTML页面的Java库,提供了一套简单易用的API来从网页中获取、操纵和解析数据。
其中,Connection类是JSoup 库中的关键组件之一,它负责建立与目标URL的连接,并封装了各种HTTP请求和响应的操作。
其中,execute方法是Connection类中的一个重要方法,它用于发送请求并获取响应,本文将重点讨论execute方法的作用、使用方法以及其内部细节。
第一部分:execute方法的作用Connection类的execute方法主要用于发送HTTP请求并获取响应,它提供了一种简单的方式来获取网页内容,并以字符串的形式返回响应结果。
通过execute方法,我们可以发送GET请求、POST请求和其他各种类型的HTTP请求,并获得服务器对请求的响应结果。
这将为我们从网页中获取数据或进行页面操作提供了强大的能力。
第二部分:execute方法的使用方法在使用execute方法之前,我们首先需要创建一个Connection对象,并使用其url方法指定需要请求的URL。
接下来,我们可以使用Connection对象的其他方法,如data、header、method等,对请求进行进一步配置。
配置完成后,我们可以调用execute方法发送请求,并获取服务器的响应结果。
首先,我们创建一个Connection对象:Connection conn = Jsoup.connect("在创建Connection对象后,我们可以使用一系列的方法对请求进行配置,如添加请求参数、设置请求头、指定请求方法等。
接下来,我们调用execute方法发送请求,并获取响应:Response response = conn.execute();通过调用execute方法,我们可以获取一个Response对象,它包含了服务器对请求的响应结果。
java执行https的请求
java执⾏https的请求普通的get和post请求只能执⾏http的请求,遇到的了https的就歇菜了,需要SSL安全证书处理。
该⽅法只能⽤jdk1.7和1.8进⾏处理,jdk1.6会报Could not generate DH keypair的错误。
1、引⼊相关依赖包jar包下载:maven:<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.5</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>2、主要类HttpClientService1 package com.sinotn.service;23 import com.alibaba.fastjson.JSONObject;4 import org.apache.http.HttpEntity;5 import ValuePair;6 import org.apache.http.client.entity.UrlEncodedFormEntity;7 import org.apache.http.client.methods.CloseableHttpResponse;8 import org.apache.http.client.methods.HttpGet;9 import org.apache.http.client.methods.HttpPost;10 import org.apache.http.client.utils.URIBuilder;11 import org.apache.http.entity.StringEntity;12 import org.apache.http.impl.client.CloseableHttpClient;13 import org.apache.http.impl.client.HttpClients;14 import org.apache.http.message.BasicHeader;15 import org.apache.http.message.BasicNameValuePair;16 import org.apache.http.util.EntityUtils;17 import org.slf4j.Logger;18 import org.slf4j.LoggerFactory;19 import java.util.ArrayList;20 import java.util.List;2122 /**23 * HttpClient发送GET、POST请求24 * @Author libin25 * @CreateDate 2018.5.28 16:5626 */27 public class HttpClientService {2829 private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);30 /**31 * 返回成功状态码32 */33 private static final int SUCCESS_CODE = 200;3435 /**36 * 发送GET请求37 * @param url 请求url38 * @param nameValuePairList 请求参数39 * @return JSON或者字符串40 * @throws Exception41 */42 public static Object sendGet(String url, List<NameValuePair> nameValuePairList) throws Exception{43 JSONObject jsonObject = null;44 CloseableHttpClient client = null;45 CloseableHttpResponse response = null;46 try{47 /**48 * 创建HttpClient对象49 */50 client = HttpClients.createDefault();51 /**52 * 创建URIBuilder53 */54 URIBuilder uriBuilder = new URIBuilder(url);55 /**56 * 设置参数57 */58 uriBuilder.addParameters(nameValuePairList);59 /**60 * 创建HttpGet61 */62 HttpGet httpGet = new HttpGet(uriBuilder.build());63 /**64 * 设置请求头部编码65 */66 httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));67 /**68 * 设置返回编码69 */70 httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));71 /**72 * 请求服务73 */74 response = client.execute(httpGet);75 /**76 * 获取响应吗77 */78 int statusCode = response.getStatusLine().getStatusCode();7980 if (SUCCESS_CODE == statusCode){81 /**82 * 获取返回对象83 */84 HttpEntity entity = response.getEntity();85 /**86 * 通过EntityUitls获取返回内容87 */88 String result = EntityUtils.toString(entity,"UTF-8");89 /**90 * 转换成json,根据合法性返回json或者字符串91 */92 try{93 jsonObject = JSONObject.parseObject(result);94 return jsonObject;95 }catch (Exception e){96 return result;97 }98 }else{99 LOGGER.error("HttpClientService-line: {}, errorMsg{}", 97, "GET请求失败!");100 }101 }catch (Exception e){102 LOGGER.error("HttpClientService-line: {}, Exception: {}", 100, e);103 } finally {104 response.close();105 client.close();106 }107 return null;108 }109110 /**111 * 发送POST请求112 * @param url113 * @param nameValuePairList114 * @return JSON或者字符串115 * @throws Exception116 */117 public static Object sendPost(String url, List<NameValuePair> nameValuePairList) throws Exception{118 JSONObject jsonObject = null;119 CloseableHttpClient client = null;120 CloseableHttpResponse response = null;121 try{122 /**123 * 创建⼀个httpclient对象124 */125 client = HttpClients.createDefault();126 /**127 * 创建⼀个post对象128 */129 HttpPost post = new HttpPost(url);130 /**131 * 包装成⼀个Entity对象132 */133 StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");134 /**135 * 设置请求的内容137 post.setEntity(entity);138 /**139 * 设置请求的报⽂头部的编码140 */141 post.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); 142 /**143 * 设置请求的报⽂头部的编码144 */145 post.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));146 /**147 * 执⾏post请求148 */149 response = client.execute(post);150 /**151 * 获取响应码152 */153 int statusCode = response.getStatusLine().getStatusCode();154 if (SUCCESS_CODE == statusCode){155 /**156 * 通过EntityUitls获取返回内容157 */158 String result = EntityUtils.toString(response.getEntity(),"UTF-8");159 /**160 * 转换成json,根据合法性返回json或者字符串161 */162 try{163 jsonObject = JSONObject.parseObject(result);164 return jsonObject;165 }catch (Exception e){166 return result;167 }168 }else{169 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 146, "POST请求失败!");170 }171 }catch (Exception e){172 LOGGER.error("HttpClientService-line: {}, Exception:{}", 149, e);173 }finally {174 response.close();175 client.close();176 }177 return null;178 }179180 /**181 * 组织请求参数{参数名和参数值下标保持⼀致}182 * @param params 参数名数组183 * @param values 参数值数组184 * @return 参数对象185 */186 public static List<NameValuePair> getParams(Object[] params, Object[] values){187 /**188 * 校验参数合法性189 */190 boolean flag = params.length>0 && values.length>0 && params.length == values.length;191 if (flag){192 List<NameValuePair> nameValuePairList = new ArrayList<>();193 for(int i =0; i<params.length; i++){194 nameValuePairList.add(new BasicNameValuePair(params[i].toString(),values[i].toString()));195 }196 return nameValuePairList;197 }else{198 LOGGER.error("HttpClientService-line: {}, errorMsg:{}", 197, "请求参数为空且参数长度不⼀致");199 }200 return null;201 }202 }3、调⽤⽅法1 package com.sinotn.service.impl;23 import com.sinotn.service.HttpClientService;4 import ValuePair;56 import java.util.List;78 /**9 * 发送post/get 测试类10 */11 public class Test {1213 public static void main(String[] args) throws Exception{14 String url = "要请求的url地址";16 * 参数值17 */18 Object [] params = new Object[]{"param1","param2"};19 /**20 * 参数名21 */22 Object [] values = new Object[]{"value1","value2"};23 /**24 * 获取参数对象25 */26 List<NameValuePair> paramsList = HttpClientService.getParams(params, values);27 /**28 * 发送get29 */30 Object result = HttpClientService.sendGet(url, paramsList);31 /**32 * 发送post33 */34 Object result2 = HttpClientService.sendPost(url, paramsList);3536 System.out.println("GET返回信息:" + result);37 System.out.println("POST返回信息:" + result2);38 }39 }4、对于发送https为了避免需要证书,所以⽤⼀个类继承DefaultHttpClient类,忽略校验过程。
发送HTTPS请求,获得网页内容的java方法
发送HTTPS请求,获得网页内容的java方法这是一个java方法,其功能是发送https请求,获得相应的页面内容..最后返回字符串/*** 发送HTTPS请求,获得网页内容* @param urlstr* @return* @throws IOException*/@Testpublic String testHtml2(String urlstr) {//System.out.println("############");String sCurrentLine;String sTotalString;sCurrentLine = "";sTotalString = "";String hsUrl = "https://localhost:8443/BestServer/login!Checking.do?string="+ urlstr;URL url ;try {url = new URL(hsUrl);HttpsURLConnection con = (HttpsURLConnection) url.openConnection();X509TrustManager xtm = new X509TrustManager() {@Overridepublic X509Certificate[] getAcceptedIssuers() {// TODO Auto-generated method stubreturn null;}@Overridepublic void checkServerTrusted(X509Certificate[] arg0, String arg1)throws CertificateException {// TODO Auto-generated method stub}@Overridepublic void checkClientTrusted(X509Certificate[] arg0, String arg1)throws CertificateException {// TODO Auto-generated method stub}};TrustManager[] tm = { xtm };SSLContext ctx = SSLContext.getInstance("TLS");ctx.init(null, tm, null);con.setSSLSocketFactory(ctx.getSocketFactory());con.setHostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String arg0, SSLSession arg1) {return true;}});InputStream l_urlStream = con.getInputStream();;BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream));while ((sCurrentLine = l_reader.readLine()) != null) {sTotalString += sCurrentLine + "\r\n";}//System.out.println(sT otalString.trim());} catch (Exception e) {e.printStackTrace();}return sT otalString.trim();}。
二、java发送https的各类请求
⼆、java发送https的各类请求导航java开发中需要调⽤其他服务的对外提供的https请求,上⼀篇写的是调⽤http,处理⽅式不太⼀样,可以参考如下代码:注:调⽤的主类⽐较简单就不写了。
pom.xml<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.10</version></dependency><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.6</version></dependency>HttpsUtil.class类package cn.cas.xjipc.yjsapplication.unit;import mons.httpclient.util.HttpURLConnection;import ponent;import java.io.*;import .URL;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import .ssl.*;@Componentpublic class HttpsUtil {private static class TrustAnyTrustManager implements X509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[]{};}}private static class TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify(String hostname, SSLSession session) {return true;}}/*** post⽅式请求服务器(https协议)** @param url 请求地址* @param content 参数* @param charset 编码* @return* @throws NoSuchAlgorithmException* @throws KeyManagementException* @throws IOException*/public String post(String url, String content, String charset)throws NoSuchAlgorithmException, KeyManagementException,IOException {String result = "";SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[]{new TrustAnyTrustManager()},new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.setDoOutput(true);conn.connect();DataOutputStream out = new DataOutputStream(conn.getOutputStream());out.write(content.getBytes(charset));// 刷新、关闭out.flush();out.close();InputStream is = conn.getInputStream();if (is != null) {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = is.read(buffer)) != -1) {outStream.write(buffer, 0, len);}is.close();byte[] array = outStream.toByteArray();result = new String(array, "utf-8");return result;}return null;}/*** put⽅式请求服务器(https协议)** @param url 请求地址* @param content 参数* @param token 编码* @return* @throws NoSuchAlgorithmException* @throws KeyManagementException* @throws IOException*/public String put(String url, String content, String token)throws NoSuchAlgorithmException, KeyManagementException,IOException {String result = "";SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[]{new TrustAnyTrustManager()},new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); conn.setRequestMethod("PUT");conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); //conn.setRequestProperty("Authorization", "xxxxx" + token);conn.connect();DataOutputStream out = new DataOutputStream(conn.getOutputStream());//out.write(content.getBytes("UTF8"));// 刷新、关闭out.flush();out.close();InputStream is = conn.getInputStream();if (is != null) {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = is.read(buffer)) != -1) {outStream.write(buffer, 0, len);}is.close();byte[] array = outStream.toByteArray();result = new String(array, "utf-8");return result;}return null;}/*** get⽅式请求服务器(https协议)** @param url 请求地址* @param content 参数* @param token 编码* @return* @throws NoSuchAlgorithmException* @throws KeyManagementException* @throws IOException*/public String get(String url, String content, String token)throws NoSuchAlgorithmException, KeyManagementException,IOException {String result = "";SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[]{new TrustAnyTrustManager()},new java.security.SecureRandom());URL httpUrl = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) httpUrl.openConnection();conn.setRequestMethod("GET");conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");//conn.setRequestProperty("Authorization", "xxxxxx" + token);conn.connect();//get⽅法与post⽅法除了conn.setRequestMethod("GET")这句不⼀样外,关于DataOutputStream out的⼏⾏⼀定要删除,否则就会报405的错误 InputStream is = conn.getInputStream();if (is != null) {ByteArrayOutputStream outStream = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = is.read(buffer)) != -1) {outStream.write(buffer, 0, len);}is.close();byte[] array = outStream.toByteArray();result = new String(array, "utf-8");return result;}return null;}}。
Java中Https发送POST请求[亲测可用]
Java中Https发送POST请求[亲测可⽤]1、直接建⼀个⼯具类放⼊即可/*** 发送https请求共⽤体*/public static JSONObject sendPost(String url,String parame,Map<String,Object> pmap) throws IOException, KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException{ // 请求结果JSONObject json = new JSONObject();PrintWriter out = null;BufferedReader in = null;String result = "";URL realUrl;HttpsURLConnection conn;String method = "POST";//查询地址String queryString = url;//请求参数获取String postpar = "";//字符串请求参数if(parame!=null){postpar = parame;}// map格式的请求参数if(pmap!=null){StringBuffer mstr = new StringBuffer();for(String str:pmap.keySet()){String val = (String) pmap.get(str);try {val=URLEncoder.encode(val,"UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}mstr.append(str+"="+val+"&");}// 最终参数postpar = mstr.toString();int lasts=stIndexOf("&");postpar=postpar.substring(0, lasts);}if(method.toUpperCase().equals("GET")){queryString+="?"+postpar;}SSLSocketFactory ssf= HttpsClientUtils.getSSFactory();try {realUrl= new URL(queryString);conn = (HttpsURLConnection)realUrl.openConnection();conn.setSSLSocketFactory(ssf);conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");conn.setRequestProperty("accept", "*/*");conn.setRequestProperty("connection", "Keep-Alive");conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");if(method.toUpperCase().equals("POST")){conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);out = new PrintWriter(conn.getOutputStream());out.print(postpar);out.flush();}else{conn.connect();}in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));String line;while ((line = in.readLine()) != null) {result += line;}json = JSONObject.fromObject(result);}finally {try {if (out != null) {out.close();}if (in != null) {in.close();}} catch (IOException ex) {ex.printStackTrace();}}return json;}2、可能需要的包import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import .URI;import .URL;import .URLEncoder;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.Random;import java.util.Set;import java.util.TreeMap;import .ssl.HttpsURLConnection;import .ssl.SSLSocketFactory;import net.sf.json.JSONObject;import mons.codec.digest.DigestUtils;import ValuePair;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.client.utils.URIBuilder;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;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;到此这篇关于Java中Https发送POST请求[亲测可⽤]的⽂章就介绍到这了,更多相关https发送post请求内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。