Java 发送https 的post请求方法

合集下载

java模拟httphttpspost请求

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发送post请求,使用multipartform-data的方式传递参数,可实现服。。。

java发送post请求,使用multipartform-data的方式传递参数,可实现服。。。

java发送post请求,使⽤multipartform-data的⽅式传递参数,可实现服。

/*** 测试上传图⽚**/public static void testUploadImage(){String url = "http://xxxtest/Api/testUploadModelBaking";String fileName = "e:/username/textures/antimap_0017.png";Map<String, String> textMap = new HashMap<String, String>();//可以设置多个input的name,valuetextMap.put("name", "testname");textMap.put("type", "2");//设置file的name,路径Map<String, String> fileMap = new HashMap<String, String>();fileMap.put("upfile", fileName);String contentType = "";//image/pngString ret = formUpload(url, textMap, fileMap,contentType);System.out.println(ret);//{"status":"0","message":"add succeed","baking_url":"group1\/M00\/00\/A8\/CgACJ1Zo-LuAN207AAQA3nlGY5k151.png"}}/*** 上传图⽚* @param urlStr* @param textMap* @param fileMap* @param contentType 没有传⼊⽂件类型默认采⽤application/octet-stream* contentType⾮空采⽤filename匹配默认的图⽚类型* @return返回response数据*/@SuppressWarnings("rawtypes")public static String formUpload(String urlStr, Map<String, String> textMap,Map<String, String> fileMap,String contentType) {String res = "";HttpURLConnection conn = null;// boundary就是request头和上传⽂件内容的分隔符String BOUNDARY = "---------------------------123821742118716";try {URL url = new URL(urlStr);conn = (HttpURLConnection) url.openConnection();conn.setConnectTimeout(5000);conn.setReadTimeout(30000);conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);conn.setRequestMethod("POST");conn.setRequestProperty("Connection", "Keep-Alive");// conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);OutputStream out = new DataOutputStream(conn.getOutputStream());// textif (textMap != null) {StringBuffer strBuf = new StringBuffer();Iterator iter = textMap.entrySet().iterator();while (iter.hasNext()) {Map.Entry entry = (Map.Entry) iter.next();String inputName = (String) entry.getKey();String inputValue = (String) entry.getValue();if (inputValue == null) {continue;}strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");strBuf.append(inputValue);}out.write(strBuf.toString().getBytes());}// fileif (fileMap != null) {Iterator iter = fileMap.entrySet().iterator();while (iter.hasNext()) {Map.Entry entry = (Map.Entry) iter.next();String inputName = (String) entry.getKey();String inputValue = (String) entry.getValue();if (inputValue == null) {continue;}File file = new File(inputValue);String filename = file.getName();//没有传⼊⽂件类型,同时根据⽂件获取不到类型,默认采⽤application/octet-streamcontentType = new MimetypesFileTypeMap().getContentType(file);//contentType⾮空采⽤filename匹配默认的图⽚类型if(!"".equals(contentType)){if (filename.endsWith(".png")) {contentType = "image/png";}else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {contentType = "image/jpeg";}else if (filename.endsWith(".gif")) {contentType = "image/gif";}else if (filename.endsWith(".ico")) {contentType = "image/image/x-icon";}}if (contentType == null || "".equals(contentType)) {contentType = "application/octet-stream";}StringBuffer strBuf = new StringBuffer();strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n"); strBuf.append("Content-Type:" + contentType + "\r\n\r\n");out.write(strBuf.toString().getBytes());DataInputStream in = new DataInputStream(new FileInputStream(file));int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = in.read(bufferOut)) != -1) {out.write(bufferOut, 0, bytes);}in.close();}}byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();out.write(endData);out.flush();out.close();// 读取返回数据StringBuffer strBuf = new StringBuffer();BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line = null;while ((line = reader.readLine()) != null) {strBuf.append(line).append("\n");}res = strBuf.toString();reader.close();reader = null;} catch (Exception e) {System.out.println("发送POST请求出错。

Java 发送https 的post请求方法

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 = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;fruitShop&gt;&lt;fruits&gt;&lt;fr uit&gt;&lt;kind&gt;萝卜&lt;/kind&gt;&lt;/fruit&gt;&lt;fruit&gt;&lt;kind&gt;菠萝&lt;/kind&gt;&lt;/fruit&gt;&lt;/fruits&gt;&lt;/fruitShop&gt;";HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);// 发起请求HttpsPost.post(httpsUrl, xmlStr);}} [java] viewplaincopyimport .ssl.HostnameVerifier;import .ssl.SSLSession;/*** 实现用于主机名验证的基接口。

java发起HTTPS请求

java发起HTTPS请求

摘要JSSE是一个SSL和TLS的纯Java实现,通过JSSE可以很容易地编程实现对HTTPS 站点的访问。

但是,如果该站点的证书未经权威机构的验证,JSSE将拒绝信任该证书从而不能访问HTTPS站点。

本文在简要介绍JSSE的基础上提出了两种解决该问题的方法。

引言过去的十几年,网络上已经积累了大量的Web应用。

如今,无论是整合原有的Web应用系统,还是进行新的Web开发,都要求通过编程来访问某些Web页面。

传统的方法是使用Socket接口,但现在很多开发平台或工具如.NET、Java或PHP 等都提供了简单的Web访问接口,使用这些接口很容易编程实现与Web应用系统的交互访问,即使要访问那些采用了HTTPS而不是HTTP的Web应用系统。

HTTPS,即安全的超文本传输协议,采用了SSL技术,被广泛使用以保证Web 应用系统的安全性。

访问Web应用的编程接口大多封装了SSL,使得访问HTTPS 和访问HTTP一样简单。

但是很多中、小型应用系统或基于局域网、校园网的应用系统所使用的证书并不是由权威的认证机构发行或者被其验证,直接使用这些编程接口将不能访问HTTPS。

本文将在简要介绍JSSE的基础上,详细描述使用JSSE访问HTTPS的方法,主要说明了如何访问带有未经验证证书的HTTPS站点。

JSSE简介Java安全套接扩展 (Java Secure Socket Extension, JSSE)是实现Internet安全通信的一系列包的集合。

它是一个SSL和TLS的纯Java实现,可以透明地提供数据加密、服务器认证、信息完整性等功能,可以使我们像使用普通的套接字一样使用JSSE建立的安全套接字。

JSSE是一个开放的标准,不只是Sun公司才能实现一个JSSE,事实上其他公司有自己实现的JSSE。

在深入了解JSSE之前,需要了解一个有关Java安全的概念:客户端的TrustStore文件。

客户端的TrustStore文件中保存着被客户端所信任的服务器的证书信息。

java中的post的方法

java中的post的方法

java中的post的方法在Java中,HTTP POST方法用于向指定的URL提交数据。

它是用来向服务器提交数据,并在服务器上创建新的资源的一种请求方法。

在Java中,我们可以使用不同的方式来实现HTTP POST请求,包括使用原生的Java API、使用第三方库或框架等。

下面我们将介绍在Java中实现HTTP POST请求的一些常用方法。

1. 使用原生的Java API实现HTTP POST请求在Java中,我们可以使用原生的Java API来实现HTTP POST请求。

下面是一个简单的例子:javaimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import .HttpURLConnection;import .URL;import java.nio.charset.StandardCharsets;public class HttpPostExample {public static void main(String[] args) throws IOException { String url = "String data = "param1=value1&param2=value2";byte[] postData = data.getBytes(StandardCharsets.UTF_8);int postDataLength = postData.length;URL obj = new URL(url);HttpURLConnection con = (HttpURLConnection)obj.openConnection();con.setDoOutput(true);con.setRequestMethod("POST");con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");con.setRequestProperty("Content-Length",Integer.toString(postDataLength));try (OutputStream os = con.getOutputStream()) {os.write(postData);}StringBuilder response = new StringBuilder();try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {String inputLine;while ((inputLine = in.readLine()) != null) {response.append(inputLine);}}System.out.println(response.toString());}}在上面的例子中,我们使用了`HttpURLConnection`来发送HTTP POST请求。

java post方法

java post方法

java post方法Java中的POST方法可以通过以下步骤实现:1. 创建URL对象,指定POST方法的网址。

javaURL url = new URL("2. 创建URLConnection对象,并将请求方法设置为POST。

javaURLConnection connection = url.openConnection(); connection.setRequestMethod("POST");3. 添加请求头信息,包括请求类型和数据格式等。

javaconnection.setRequestProperty("Content-Type", "application/json");4. 添加请求体信息,也就是需要传递的参数。

javaconnection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonRequestBody);out.flush();out.close();其中,jsonRequestBody可以是一个JSON格式的字符串。

5. 发送请求并获取响应。

javaint responseCode = connection.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String response = in.readLine();in.close();6. 处理响应信息,例如将JSON格式的字符串转换为Java对象。

javaGson gson = new Gson();MyResponseObject responseObj = gson.fromJson(response, MyResponseObject.class);其中,MyResponseObject是一个Java类,在实现时需要根据实际需求定义其属性。

Java发送HTTPPOST请求(内容为xml格式)

Java发送HTTPPOST请求(内容为xml格式)

Java发送HTTPPOST请求(内容为xml格式)今天在给平台⽤户提供http简单接⼝的时候,顺便写了个调⽤的Java类供他参考。

服务器地址:http://5.0.217.50:17001/VideoSend服务器提供的是xml格式的http接⼝,接⼝定义如下:<!--视频点送: videoSend--><videoSend><header><sid>%s</sid><type>service</type></header><service name="videoSend"><fromNum>%s</fromNum><toNum>%s</toNum> <!--需要接通的⽤户的电话号码 --><videoPath>%s</videoPath> <!--视频⽂件路径 --><chargeNumber>%s</chargeNumber> <!--计费号码 --></service></videoSend><!--视频点送返回结果: videoSendResult--><videoSend><header><sid>%s</sid><type>service</type></header><service name="videoSendResult">rescode>%s</rescode> <!--0000:视频点送成功,0001:请求参数信息错误, 0002:接通⽤户失败--></service></videoSend>对应调⽤端的Java代码(只是个demo,参数都暂时写死了)如下:import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import .MalformedURLException;import .URL;import .URLConnection;public class HttpPostTest {void testPost(String urlStr) {try {URL url = new URL(urlStr);URLConnection con = url.openConnection();con.setDoOutput(true);con.setRequestProperty("Pragma:", "no-cache");con.setRequestProperty("Cache-Control", "no-cache");con.setRequestProperty("Content-Type", "text/xml");OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());String xmlInfo = getXmlInfo();System.out.println("urlStr=" + urlStr);System.out.println("xmlInfo=" + xmlInfo);out.write(new String(xmlInfo.getBytes("ISO-8859-1")));out.flush();out.close();BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));String line = "";for (line = br.readLine(); line != null; line = br.readLine()) {System.out.println(line);}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}private String getXmlInfo() {StringBuilder sb = new StringBuilder();sb.append("<videoSend>");sb.append(" <header>");sb.append(" <sid>1</sid>");sb.append(" <type>service</type>");sb.append(" </header>");sb.append(" <service name=\"videoSend\">");sb.append(" <fromNum>0000021000011001</fromNum>");sb.append(" <toNum>33647405</toNum>");sb.append(" <videoPath>mnt/5.0.217.50/resources/80009.mov</videoPath>"); sb.append(" <chargeNumber>0000021000011001</chargeNumber>");sb.append(" </service>");sb.append("</videoSend>");return sb.toString();}public static void main(String[] args) {String url = "http://5.0.217.50:17001/VideoSend";new HttpPostTest().testPost(url);}}。

post请求用法

post请求用法

post请求用法Post请求用法Post请求是HTTP协议中的一种请求方式,它通常用于向服务器提交数据。

相比于Get请求,Post请求可以提交更多的数据,并且不会将数据暴露在URL中。

本文将详细介绍Post请求的用法。

一、Post请求的基本概念1.1 Post请求的定义Post请求是一种HTTP协议中的请求方式,它通常用于向服务器提交数据。

1.2 Post请求与Get请求的区别相比于Get请求,Post请求可以提交更多的数据,并且不会将数据暴露在URL中。

Get请求通常用于获取数据,而Post请求则用于提交数据。

二、使用Postman进行Post请求2.1 下载并安装Postman首先需要下载并安装一个名为“Postman”的工具,它是一款功能强大、易于使用的API测试工具。

可以从官网上下载到最新版本的Postman,并在安装过程中选择安装所需组件。

2.2 创建一个新的Request打开Postman后,点击左上角“New”按钮创建一个新的Request。

然后选择“POST”作为Request类型,并输入目标URL地址。

2.3 添加Header和Body信息在下方Headers栏和Body栏中分别添加所需信息。

Headers栏中可以添加自定义Header信息,例如Content-Type等;Body栏则可以添加需要提交到服务器端的数据信息。

2.4 发送Request并查看Response点击右上角“Send”按钮发送Request,并在下方的Response栏中查看服务器返回的响应信息。

可以根据需要对Response进行解析和处理。

三、使用Java代码进行Post请求3.1 使用HttpURLConnection类Java中可以使用HttpURLConnection类来进行Post请求。

首先需要创建一个URL对象并打开连接,然后设置请求方式为POST,添加Header信息,最后将数据写入请求流中并发送请求。

java发送post请求并下载返回文件

java发送post请求并下载返回文件

java发送post请求并下载返回⽂件直接上代码import java.io.*;import .HttpURLConnection;import .URL;import .URLEncoder;import java.util.*;public class ExportPost {public static String url = "http://localhost:8088/file/xxx/download2";public static String cookie = "cookie";public static void main(String[] args) throws Exception {getInternetRes("D:\\demoefile",url,"a.pdf");}public static void getInternetRes(String newUrl, String oldUrl, String fileName) throws Exception {URL url = null;HttpURLConnection con = null;InputStream in = null;FileOutputStream out = null;try {url = new URL(oldUrl);//建⽴http连接,得到连接对象con = (HttpURLConnection) url.openConnection();//设置通⽤的请求头属性con.setDoOutput(true);con.setDoInput(true);con.setRequestMethod("POST"); // 默认是 GET⽅式con.setUseCaches(false); // Post 请求不能使⽤缓存con.setInstanceFollowRedirects(true); //设置本次连接是否⾃动重定向con.setRequestProperty("User-Agent", "Mozilla/5.0");con.setRequestProperty("Content-Type", "application/form-data");// con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// con.setRequestProperty("Content-Type","application/form-data;charset=utf-8");// boundary就是request头和上传⽂件内容的分隔符String BOUNDARY = "---------------------------123821742118716";con.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);con.setRequestProperty("Connection","Keep-Alive");//设置与服务器保持连接con.setRequestProperty("Accept-Language", "zh-CN,zh;0.9");con.setRequestProperty("cookie",cookie);StringBuilder sb2 = new StringBuilder();sb2.append("\r\n").append("--").append(BOUNDARY).append("\r\n");sb2.append("Content-Disposition: form-data; name=\"no\"\r\n\r\n");sb2.append("xxx");sb2.append("\r\n").append("--").append(BOUNDARY).append("\r\n");sb2.append("Content-Disposition: form-data; name=\"json\"\r\n\r\n");sb2.append("{\"id\": \"123456\",\"mc\": \"测试名称\"}");con.connect();OutputStream outputStream = con.getOutputStream();outputStream.write(sb2.toString().getBytes());byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();outputStream.write(endData);outputStream.flush();outputStream.close();//输⼊流读取⽂件in = con.getInputStream();//转化为byte数组byte[] data = getByteData(in);//建⽴存储的⽬录、保存的⽂件名File file = new File(newUrl+ DateUtil.formatDate(new Date()));if (!file.exists()) {file.mkdirs();}//修改⽂件名⽤id重命名File res = new File(file + File.separator + fileName);//写⼊输出流out = new FileOutputStream(res);out.write(data);// ("下载 successfully!");System.out.println("下载 successfully!");} catch (IOException e) {// logger.error("下载出错!"+e.toString());System.out.println("下载出错!"+e.toString());} finally {//关闭流try {if (null != out){out.close();}if (null != in){in.close();}} catch (IOException e) {// logger.error("下载出错!"+e.toString());System.out.println("下载出错!"+e.toString());}}}/**** @Title: getByteData* @Description: 从输⼊流中获取字节数组* @author zml* @date Sep 12, 2017 7:38:57 PM*/private static byte[] getByteData(InputStream in) throws IOException { byte[] b = new byte[1024];ByteArrayOutputStream bos = new ByteArrayOutputStream();int len = 0;while ((len = in.read(b)) != -1) {bos.write(b, 0, len);}if(null!=bos){bos.close();}return bos.toByteArray();}}。

Java中Https发送POST请求[亲测可用]

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请求内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

JAVA模拟HTTPpost请求上传文件

JAVA模拟HTTPpost请求上传文件

JAVA模拟HTTPpost请求上传⽂件在开发中,我们使⽤的⽐较多的HTTP请求⽅式基本上就是GET、POST。

其中GET⽤于从服务器获取数据,POST主要⽤于向服务器提交⼀些表单数据,例如⽂件上传等。

⽽我们在使⽤HTTP请求时中遇到的⽐较⿇烦的事情就是构造⽂件上传的HTTP报⽂格式,这个格式虽说也⽐较简单,但也⽐较容易出错。

今天我们就⼀起来学习HTTP POST的报⽂格式以及通过来模拟⽂件上传的请求。

⾸先我们来看⼀个POST的报⽂请求,然后我们再来详细的分析它。

POST报⽂格式[plain]1. POST /api/feed/ HTTP/1.12. Accept-Encoding: gzip3. Content-Length: 2258734. Content-Type: multipart/form-data; boundary=OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp5. Host: 6. Connection: Keep-Alive7.8. --OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp9. Content-Disposition: form-data; name="lng"10. Content-Type: text/plain; charset=UTF-811. Content-Transfer-Encoding: 8bit12.13. 116.36154514. --OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp15. Content-Disposition: form-data; name="lat"16. Content-Type: text/plain; charset=UTF-817. Content-Transfer-Encoding: 8bit18.19. 39.97900620. --OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp21. Content-Disposition: form-data; name="images"; filename="/storage/emulated/0/Camera/jdimage/1xh0e3yyfmpr2e35tdowbavrx.jpg"22. Content-Type: application/octet-stream23. Content-Transfer-Encoding: binary24.25. 这⾥是图⽚的⼆进制数据26. --OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp--这⾥我们提交的是经度、纬度和⼀张图⽚(图⽚数据⽐较长,⽽且⽐较杂乱,这⾥省略掉了)。

JAVA发送POSTGETPUTDELETE请求,HEADER传参,BODY参数为JSON格式

JAVA发送POSTGETPUTDELETE请求,HEADER传参,BODY参数为JSON格式

JAVA发送POSTGETPUTDELETE请求,HEADER传参,BODY参数为JSON格式1、maven引⼊<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.4</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5</version></dependency>2、封装post请求⽅法public static String httpPost(String url,Map map){// 返回bodyString body = null;// 获取连接客户端⼯具CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse httpResponse=null;// 2、创建⼀个HttpPost请求HttpPost post = new HttpPost(url);// 5、设置header信息 /**header中通⽤属性*/ post.setHeader("Accept","*/*"); post.setHeader("Accept-Encoding","gzip, deflate"); post.setHeader("Cache-Control","no-cache"); post.setHeader("Connection", "keep-alive"); post.setHeader("Content-Type", "application/json;charset=UTF-8"); /**业务参数*/ post.setHeader("test1","test1"); post.setHeader("test2",2);// 设置参数if (map != null) {//System.out.println(JSON.toJSONString(map));try {StringEntity entity1=new StringEntity(JSON.toJSONString(map),"UTF-8");entity1.setContentEncoding("UTF-8");entity1.setContentType("application/json");post.setEntity(entity1);// 7、执⾏post请求操作,并拿到结果httpResponse = httpClient.execute(post);// 获取结果实体HttpEntity entity = httpResponse.getEntity();if (entity != null) {// 按指定编码转换结果实体为String类型body = EntityUtils.toString(entity, "UTF-8");}try {httpResponse.close();httpClient.close();} catch (IOException e) {e.printStackTrace();}} catch (Exception e) {e.printStackTrace();}}return body;}3、封装GET请求⽅法public static String httpGet(String url){// 获取连接客户端⼯具CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse httpResponse=null;String finalString = null;HttpGet httpGet = new HttpGet(url);/**公共参数添加⾄httpGet*//**header中通⽤属性*/ httpGet.setHeader("Accept","*/*"); httpGet.setHeader("Accept-Encoding","gzip, deflate"); httpGet.setHeader("Cache-Control","no-cache"); httpGet.setHeader("Connection", "keep-alive"); httpGet.setHeader("Content-Type", "application/json;charset=UTF-8"); /**业务参数*/ httpGet.setHeader("test1","test1"); httpGet.setHeader("test2",2);try {httpResponse = httpClient.execute(httpGet);HttpEntity entity = httpResponse.getEntity();finalString= EntityUtils.toString(entity, "UTF-8");try {httpResponse.close();httpClient.close();} catch (IOException e) {e.printStackTrace();}} catch (IOException e) {e.printStackTrace();}return finalString;}4、封装put请求public static String httpPut(String url,Map map){String encode = "utf-8";//HttpClients.createDefault()等价于 HttpClientBuilder.create().build();CloseableHttpClient closeableHttpClient = HttpClients.createDefault();HttpPut httpput = new HttpPut(url);// 5、设置header信息/**header中通⽤属性*/ httpput.setHeader("Accept","*/*"); httpput.setHeader("Accept-Encoding","gzip, deflate"); httpput.setHeader("Cache-Control","no-cache"); httpput.setHeader("Connection", "keep-alive"); httpput.setHeader("Content-Type", "application/json;charset=UTF-8"); /**业务参数*/ httpput.setHeader("test1","test1"); httpput.setHeader("test2",2);//组织请求参数StringEntity stringEntity = new StringEntity(JSON.toJSONString(map), encode); httpput.setEntity(stringEntity);String content = null;CloseableHttpResponse httpResponse = null;try {//响应信息httpResponse = closeableHttpClient.execute(httpput);HttpEntity entity = httpResponse.getEntity();content = EntityUtils.toString(entity, encode);} catch (Exception e) {e.printStackTrace();}finally{try {httpResponse.close();} catch (IOException e) {e.printStackTrace();}}try {closeableHttpClient.close(); //关闭连接、释放资源} catch (IOException e) {e.printStackTrace();}return content;}5、封装delete请求public static String httpDelete(String url){//HttpResponse response = new HttpResponse();String encode = "utf-8";String content = null;//since 4.3 不再使⽤ DefaultHttpClientCloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();HttpDelete httpdelete = new HttpDelete(url);// 5、设置header信息/**header中通⽤属性*/ httpdelete.setHeader("Accept","*/*"); httpdelete.setHeader("Accept-Encoding","gzip, deflate"); httpdelete.setHeader("Cache-Control","no-cache"); httpdelete.setHeader("Connection", "keep-alive"); httpdelete.setHeader("Content-Type", "application/json;charset=UTF-8"); /**业务参数*/ httpdelete.setHeader("test1","test1"); httpdelete.setHeader("test2",2);CloseableHttpResponse httpResponse = null;try {httpResponse = closeableHttpClient.execute(httpdelete);HttpEntity entity = httpResponse.getEntity();content = EntityUtils.toString(entity, encode);} catch (Exception e) {e.printStackTrace();}finally{try {httpResponse.close();} catch (IOException e) {e.printStackTrace();}}try { //关闭连接、释放资源closeableHttpClient.close();} catch (IOException e) {e.printStackTrace();}return content;}。

java post请求传递参数

java post请求传递参数

java post请求传递参数Java是一种广泛应用的编程语言,它有着高效稳定的特点。

在Java开发中,我们常常需要进行HTTP请求的相关操作,尤其是针对POST请求的参数传递,这是一个比较常见的需求。

在本文中,我们将详细介绍Java POST请求传递参数相关知识。

一、POST请求基础知识在HTTP请求中,GET和POST请求是最常用的两种方式。

GET请求通过URL参数传递参数,POST请求则是通过HTTP请求体传递参数。

相比于GET请求,POST请求的参数更加安全,也更容易读取和理解。

在Java中,我们可以通过HttpURLConnection和HttpClient两个类进行POST请求的相关操作,这两个类分别代表了Java中两种主流的HTTP请求方式:Java标准库中的HttpURLConnection和第三方库HttpClient。

其中.HttpURLConnection是Java SDK自带的HTTP请求接口,可以直接使用。

而Apache HttpClient则是很多Java项目中使用的第三方HTTP请求库,其功能更加强大灵活。

二、使用HttpURLConnection进行POST请求传递参数通过HttpURLConnection发送POST请求需要完成以下几个步骤:1. 创建一个URL对象,该对象持有需要发送请求的地址2. 调用URL对象的openConnection()方法,得到HttpURLConnection对象3. 设置请求方式为POST,通过setRequestMethod("POST")方法4. 设置请求头信息5. 设置请求体参数,通过OutputStream对象写入数据6. 发送请求,获得响应如下是一个Java代码实例,用于演示如何通过HttpURLConnection发送POST请求,并传递参数:```java public void sendPostRequest(String urlStr, String paramStr) throws Exception { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Connection", "Keep-Alive"); conn.setUseCaches(false);conn.setDoOutput(true);OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); osw.write(paramStr); osw.flush(); osw.close();InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null){ sb.append(line); } is.close(); br.close();System.out.println(sb.toString()); } ```在sendPostRequest()方法中,首先创建一个URL对象,并调用openConnection()方法获取HttpURLConnection对象。

Java发送https请求代码实例

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发送httpgetpost请求,调用接口方法

Java发送httpgetpost请求,调用接口方法

Java发送httpgetpost请求,调⽤接⼝⽅法由于项⽬中要⽤,所以找了⼀些资料,整理下来。

例1:使⽤ HttpClient (commons-httpclient-3.0.jar1import java.io.ByteArrayInputStream;2import java.io.ByteArrayOutputStream;3import java.io.IOException;4import java.io.InputStream;56import mons.httpclient.HttpClient;7import mons.httpclient.methods.InputStreamRequestEntity;8import mons.httpclient.methods.PostMethod;9import mons.httpclient.methods.RequestEntity;1011public class HttpTool {1213/**14 * 发送post请求15 *16 * @param params17 * 参数18 * @param requestUrl19 * 请求地址20 * @param authorization21 * 授权书22 * @return返回结果23 * @throws IOException24*/25public static String sendPost(String params, String requestUrl,26 String authorization) throws IOException {2728byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为⼆进制流29 HttpClient httpClient = new HttpClient();// 客户端实例化30 PostMethod postMethod = new PostMethod(requestUrl);31//设置请求头Authorization32 postMethod.setRequestHeader("Authorization", "Basic " + authorization);33// 设置请求头 Content-Type34 postMethod.setRequestHeader("Content-Type", "application/json");35 InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,36 requestBytes.length);37 RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,38 requestBytes.length, "application/json; charset=utf-8"); // 请求体39 postMethod.setRequestEntity(requestEntity);40 httpClient.executeMethod(postMethod);// 执⾏请求41 InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流42byte[] datas = null;43try {44 datas = readInputStream(soapResponseStream);// 从输⼊流中读取数据45 } catch (Exception e) {46 e.printStackTrace();47 }48 String result = new String(datas, "UTF-8");// 将⼆进制流转为String49// 打印返回结果50// System.out.println(result);5152return result;5354 }5556/**57 * 从输⼊流中读取数据58 *59 * @param inStream60 * @return61 * @throws Exception62*/63public static byte[] readInputStream(InputStream inStream) throws Exception {64 ByteArrayOutputStream outStream = new ByteArrayOutputStream();65byte[] buffer = new byte[1024];66int len = 0;67while ((len = inStream.read(buffer)) != -1) {68 outStream.write(buffer, 0, len);69 }70byte[] data = outStream.toByteArray();71 outStream.close();72 inStream.close();73return data;74 }75 }例2:1import java.io.BufferedReader;2import java.io.IOException;3import java.io.InputStream;4import java.io.InputStreamReader;5import java.io.OutputStreamWriter;6import java.io.UnsupportedEncodingException;7import .HttpURLConnection;8import .InetSocketAddress;9import .Proxy;10import .URL;11import .URLConnection;12import java.util.List;13import java.util.Map;1415/**16 * Http请求⼯具类17*/18public class HttpRequestUtil {19static boolean proxySet = false;20static String proxyHost = "127.0.0.1";21static int proxyPort = 8087;22/**23 * 编码24 * @param source25 * @return26*/27public static String urlEncode(String source,String encode) {28 String result = source;29try {30 result = .URLEncoder.encode(source,encode);31 } catch (UnsupportedEncodingException e) {32 e.printStackTrace();33return "0";34 }35return result;36 }37public static String urlEncodeGBK(String source) {38 String result = source;39try {40 result = .URLEncoder.encode(source,"GBK");41 } catch (UnsupportedEncodingException e) {42 e.printStackTrace();43return "0";44 }45return result;46 }47/**48 * 发起http请求获取返回结果49 * @param req_url 请求地址50 * @return51*/52public static String httpRequest(String req_url) {53 StringBuffer buffer = new StringBuffer();54try {55 URL url = new URL(req_url);56 HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();5758 httpUrlConn.setDoOutput(false);59 httpUrlConn.setDoInput(true);60 httpUrlConn.setUseCaches(false);6162 httpUrlConn.setRequestMethod("GET");63 httpUrlConn.connect();6465// 将返回的输⼊流转换成字符串66 InputStream inputStream = httpUrlConn.getInputStream();67 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");68 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);6970 String str = null;71while ((str = bufferedReader.readLine()) != null) {72 buffer.append(str);73 }74 bufferedReader.close();75 inputStreamReader.close();76// 释放资源77 inputStream.close();78 inputStream = null;79 httpUrlConn.disconnect();8081 } catch (Exception e) {82 System.out.println(e.getStackTrace());83 }84return buffer.toString();85 }8687/**88 * 发送http请求取得返回的输⼊流89 * @param requestUrl 请求地址90 * @return InputStream91*/92public static InputStream httpRequestIO(String requestUrl) {93 InputStream inputStream = null;94try {95 URL url = new URL(requestUrl);96 HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();97 httpUrlConn.setDoInput(true);98 httpUrlConn.setRequestMethod("GET");99 httpUrlConn.connect();100// 获得返回的输⼊流101 inputStream = httpUrlConn.getInputStream();102 } catch (Exception e) {103 e.printStackTrace();104 }105return inputStream;106 }107108109/**110 * 向指定URL发送GET⽅法的请求111 *112 * @param url113 * 发送请求的URL114 * @param param115 * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。

JAVAHttpURLConnection发送post请求,数据格式为form-data,。。。

JAVAHttpURLConnection发送post请求,数据格式为form-data,。。。

JAVAHttpURLConnection发送post请求,数据格式为form-data,。

public static String postFormData(String url, Map<String, Object> map) throws Exception {BufferedReader in = null;URL urls = new URL(url);HttpURLConnection connection = null;OutputStream outputStream = null;String rs = "";try {connection = (HttpURLConnection) urls.openConnection();connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----footfoodapplicationrequestnetwork");connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");connection.setRequestProperty("Accept", "*/*");connection.setRequestProperty("Range", "bytes=" + "");connection.setConnectTimeout(8000);connection.setReadTimeout(20000);connection.setRequestMethod("POST");StringBuffer buffer = new StringBuffer();outputStream = connection.getOutputStream();Set<Entry<String, Object>> entries = map.entrySet();for (Entry<String, Object> entry : entries) {// 每次都清空buffer,避免写⼊上次的数据buffer.delete(0, buffer.length());buffer.append("------footfoodapplicationrequestnetwork\r\n");Object value = entry.getValue();if (!(value instanceof File)) {buffer.append("Content-Disposition: form-data; name=\"");buffer.append(entry.getKey());buffer.append("\"\r\n\r\n");buffer.append(entry.getValue());buffer.append("\r\n");outputStream.write(buffer.toString().getBytes());// System.out.println(buffer.toString());} else {buffer.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"; filename=\"" + ((File) entry.getValue()).getName() + "\"\r\n"); buffer.append("Content-Type: " + "zip" + "\r\n\r\n");// System.out.println(buffer.toString());outputStream.write(buffer.toString().getBytes());File file = (File) entry.getValue();DataInputStream ins = new DataInputStream(new FileInputStream(file));int bytes = 0;byte[] bufferOut = new byte[1024];while ((bytes = ins.read(bufferOut)) != -1) {outputStream.write(bufferOut, 0, bytes);// System.out.print("A");}// ⽂件流后⾯添加换⾏,否则⽂件后⾯的⼀个参数会丢失outputStream.write("\r\n".getBytes());// System.out.println("\r\n");}}if (entries != null && map.size() > 0) {buffer.delete(0, buffer.length());buffer.append("------footfoodapplicationrequestnetwork--\r\n");// System.out.println(buffer.toString());}outputStream.write(buffer.toString().getBytes());try {try {connection.connect();if (connection.getResponseCode() == 200) {in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));String line = "";while ((line = in.readLine()) != null) {rs += line;}}} catch (Exception e) {System.out.println("发⽣异常");rs = null;}return rs;} finally {try {outputStream.close();if (in != null){in.close();}} catch (Exception e) {}outputStream = null;if (connection != null)connection.disconnect();connection = null;}}public static void main(String[] args) {String url = "http://localhost:";HashMap<String, Object> map = new HashMap<String, Object>();map.put("lineSta", "0121");map.put("devTypeId", "04");map.put("deviceId", "034");map.put("inOutType", "10");map.put("versionNo", "1016");map.put("deviceTime", String.valueOf(System.currentTimeMillis()));File file = new File("file/01.zip"); // ⽂件路径,基于项⽬,在项⽬根⽬录建⽴file⽂件夹,01.zipmap.put("logFileName", file.getName()); // 上传⽂件名,与⽂件保持⼀致,这⾥⾃动获取map.put("uploadFile",file); // 上传的⽂件String returnStr2 = "";try {returnStr2 = HttpUtil.postFormData(url, map);} catch (Exception e) {System.out.println("上传,发⽣异常" + e.getMessage());}System.out.println(returnStr2);}使⽤java from-data原始⽅式上传过于⿇烦,需要⼿动组装数据,过于⿇烦,这⾥帮⼤家写了⼀个demo,直接调⽤即可,启动想要看到form-data的原始数据格式,请解除System.out.print 打印注释。

java发送https忽略证书

java发送https忽略证书

java发送https忽略证书 /*** 发送post请求* @param urlStr* @param param* @return*/public static String doPostReq(String urlStr,String param){String result = "";BufferedReader bufferedReader = null;InputStream inputStream = null;try {trustAllHosts();URL url = new URL(urlStr);//HttpURLConnection conn = (HttpURLConnection) url.openConnection();HttpURLConnection conn = null;// 通过请求地址判断请求类型(http或者是https)if (url.getProtocol().toLowerCase().equals("https")) {HttpsURLConnection https = (HttpsURLConnection) url.openConnection();https.setHostnameVerifier(DO_NOT_VERIFY);conn = https;} else {conn = (HttpURLConnection) url.openConnection();}conn.setRequestMethod("POST");//设置请求⽅式conn.setConnectTimeout(15000);//设置连接超时时间conn.setReadTimeout(60000);//设置读取远程超时时间conn.setDoInput(true);conn.setDoOutput(true);conn.setRequestProperty("Content-type","application/json; charset=utf-8");conn.setRequestProperty("Accept","text/xml,text/javascript,text/html,application/json");OutputStream outputStream = conn.getOutputStream();//通过连接对象获取输出流outputStream.write(param.getBytes());//通过输出流对象将参数传输出去,它是通过字节数组写出去的System.out.println("respCode:"+conn.getResponseCode());if (conn.getResponseCode() == 200){inputStream = conn.getInputStream();ByteArrayOutputStream baos=new ByteArrayOutputStream();byte[] buf = new byte[1024];int len = 0;while((len=inputStream.read(buf))!=-1){baos.write(buf, 0, len);}baos.flush();result = baos.toString();} //如果响应码是307则重新发起请求if(307 == conn.getResponseCode()) {String redirectUrl = conn.getHeaderField("Location");if(redirectUrl != null && !redirectUrl.isEmpty()) {urlStr = redirectUrl;return doPostReq(urlStr,param);}}}catch (Exception e){e.printStackTrace();}finally {try {if (null != bufferedReader){bufferedReader.close();}if (null != inputStream){inputStream.close();}}catch (IOException e){e.printStackTrace();}}return result;}private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {public boolean verify(String hostname, SSLSession session) {return true;}};private static void trustAllHosts() {// Create a trust manager that does not validate certificate chainsTrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[] {};}public void checkClientTrusted(X509Certificate[] chain, String authType) { }public void checkServerTrusted(X509Certificate[] chain, String authType) { }} };// Install the all-trusting trust managertry {SSLContext sc = SSLContext.getInstance("TLS");sc.init(null, trustAllCerts, new java.security.SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) {e.printStackTrace();}}。

java中两种发起POST请求,并接收返回的响应内容的方式

java中两种发起POST请求,并接收返回的响应内容的方式

2、利用java自带的.*包下提供的工具类
代码如下:
/** * 利用URL发起POST请求,并接收返回信息 * * @param url 请求URL * @param message 请求参数 * @return 响应内容 */ @Override public String transport(String url, String message) { StringBuffer sb = new StringBuffer(); try { URL urls = new URL(url); HttpURLConnection uc = (HttpURLConnection) urls.openConnection(); uc.setRequestMethod("POST"); uc.setRequestProperty("content-type", ""); uc.setRequestProperty("charset", "UTF-8"); uc.setDoOutput(true); uc.setDoInput(true); uc.setReadTimeout(10000); uc.setConnectTimeout(10000); OutputStream os = uc.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); dos.write(message.getBytes("utf-8")); dos.flush(); os.close(); BufferedReader in = new BufferedReader(new InputStreamReader(uc .getInputStream(), "utf-8")); String readLine = ""; while ((readLine = in.readLine()) != null) { sb.append(readLine); } in.close(); } catch (Exception e) { log.error(e.getMessage(), e); } return sb.toString(); }
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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 = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;&lt;fruitShop&gt;&lt;fruits&gt;&lt;fr uit&gt;&lt;kind&gt;萝卜&lt;/kind&gt;&lt;/fruit&gt;&lt;fruit&gt;&lt;kind&gt;菠萝&lt;/kind&gt;&lt;/fruit&gt;&lt;/fruits&gt;&lt;/fruitShop&gt;";HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);// 发起请求HttpsPost.post(httpsUrl, xmlStr);}} [java] viewplaincopyimport .ssl.HostnameVerifier;import .ssl.SSLSession;/*** 实现用于主机名验证的基接口。

* 在握手期间,如果URL 的主机名和服务器的标识主机名不匹配,则验证机制可以回调此接口的实现程序来确定是否应该允许此连接。

*/public class MyHostnameVerifier implements HostnameVerifier {@Overridepublic boolean verify(String hostname, SSLSession session) {if("localhost".equals(hostname)){return true;} else {return false;}}} 接收请求的Web应用:web.xml[html] viewplaincopy&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="2.5"xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance" xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;servlet&gt;&lt;servlet-name&gt;rollBack&lt;/servlet-name&gt;&lt;servlet-class&gt;rollBack&lt;/servlet-class&gt;&lt;/servlet&gt;&lt;servlet-mapping&gt;&lt;servlet-name&gt;rollBack&lt;/servlet-name&gt;&lt;url-pattern&gt;/httpsPost&lt;/url-pattern&gt;&lt;/servlet-mapping&gt;&lt;welcome-file-list&gt;&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;&lt;/welcome-file-list&gt;&lt;/web-app&gt;rollBack servlet[java] viewplaincopyimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import javax.servlet.ServletException;import javax.servlet.ServletInputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class rollBack extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //获取请求流ServletInputStream sis =request.getInputStream();BufferedReader in = new BufferedReader(new InputStreamReader(sis));String line;if((line = in.readLine()) != null){System.out.println(line);}in.close();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { this.doGet(request, response);}}。

相关文档
最新文档