1 需求
2 接口
Class HttpURLConnection
java.lang.Object
java.net.URLConnection
java.net.HttpURLConnection
public abstract class HttpURLConnection extends URLConnection
Field Detail
Constructor Detail
- protected HttpURLConnection(URL u)
Method Detail
- public void setRequestMethod(String method) throws ProtocolException
- public int getResponseCode() throws IOException
Class URLConnection
java.lang.Object
java.net.URLConnection
public abstract class URLConnection extends Object
Field Detail
Constructor Detail
Method Detail
- public InputStream getInputStream() throws IOException
Class URL
java.lang.Object
java.net.URL
public final class URL extends Object implements Serializable
Constructor Detail
- public URL(String spec) throws MalformedURLException
Method Detail
- public URLConnection openConnection() throws IOException
- public URLConnection openConnection(Proxy proxy) throws IOException
3 示例
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- /**
- * 第一步,创建远程连接
- * 第二步,设置连接方式(get、post、put。。。)
- * 第三步,设置连接超时时间
- * 第四步,设置响应读取时间
- * 第五步,发起请求
- * 第六步,获取请求数据
- * 第七步,关闭连接
- */
- public class Test {
- public static void main(String[] args) {
-
- StringBuffer result = new StringBuffer();
-
- try {
- // 创建连接
- URL url = new URL("http://www.dvwa.com/login.php");
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- // 设置请求方式
- connection.setRequestMethod("GET");
- // 设置连接超时时间
- connection.setReadTimeout(15000);
-
- // 开始连接
- connection.connect();
-
- // 获取请求数据
- if (connection.getResponseCode() == 200) {
- InputStream is = connection.getInputStream();
- if (is != null) {
- InputStreamReader ir = new InputStreamReader(is, "UTF-8");
- BufferedReader br = new BufferedReader(ir);
- String line = null;
- while ((line = br.readLine()) != null) {
- result.append(line);
- }
- }
- }
-
- //
- connection.disconnect();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- System.out.println(result);
- }
- }
3.X 需求:文件上传
- import java.io.BufferedInputStream;
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.Iterator;
- import java.util.Map;
-
- /**
- * Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,
- * 但不够简便;
- *
- * 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求
- * 4.以输入流的形式获取返回内容 5.关闭输入流
- *
- * @author H__D
- *
- */
- public class Test {
-
-
- /**
- * 多文件上传的方法
- *
- * @param actionUrl:上传的路径
- * @param uploadFilePaths:需要上传的文件路径,数组
- * @return
- */
- @SuppressWarnings("finally")
- public static String uploadFile(String actionUrl, String[] uploadFilePaths) {
- String end = "\r\n";
- String twoHyphens = "--";
- String boundary = "*****";
-
- DataOutputStream ds = null;
- InputStream inputStream = null;
- InputStreamReader inputStreamReader = null;
- BufferedReader reader = null;
- StringBuffer resultBuffer = new StringBuffer();
- String tempLine = null;
-
- try {
- // 统一资源
- URL url = new URL(actionUrl);
- // 连接类的父类,抽象类
- URLConnection urlConnection = url.openConnection();
- // http的连接类
- HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
-
- // 设置是否从httpUrlConnection读入,默认情况下是true;
- httpURLConnection.setDoInput(true);
- // 设置是否向httpUrlConnection输出
- httpURLConnection.setDoOutput(true);
- // Post 请求不能使用缓存
- httpURLConnection.setUseCaches(false);
- // 设定请求的方法,默认是GET
- httpURLConnection.setRequestMethod("POST");
- // 设置字符编码连接参数
- httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
- // 设置字符编码
- httpURLConnection.setRequestProperty("Charset", "UTF-8");
- // 设置请求内容类型
- httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
-
- // 设置DataOutputStream
- ds = new DataOutputStream(httpURLConnection.getOutputStream());
- for (int i = 0; i < uploadFilePaths.length; i++) {
- String uploadFile = uploadFilePaths[i];
- String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
- ds.writeBytes(twoHyphens + boundary + end);
- ds.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename
- + "\"" + end);
- ds.writeBytes(end);
- FileInputStream fStream = new FileInputStream(uploadFile);
- int bufferSize = 1024;
- byte[] buffer = new byte[bufferSize];
- int length = -1;
- while ((length = fStream.read(buffer)) != -1) {
- ds.write(buffer, 0, length);
- }
- ds.writeBytes(end);
- /* close streams */
- fStream.close();
- }
- ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
- /* close streams */
- ds.flush();
- if (httpURLConnection.getResponseCode() >= 300) {
- throw new Exception(
- "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
- }
-
- if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
- inputStream = httpURLConnection.getInputStream();
- inputStreamReader = new InputStreamReader(inputStream);
- reader = new BufferedReader(inputStreamReader);
- tempLine = null;
- resultBuffer = new StringBuffer();
- while ((tempLine = reader.readLine()) != null) {
- resultBuffer.append(tempLine);
- resultBuffer.append("\n");
- }
- }
-
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } finally {
- if (ds != null) {
- try {
- ds.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if (inputStreamReader != null) {
- try {
- inputStreamReader.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if (inputStream != null) {
- try {
- inputStream.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- return resultBuffer.toString();
- }
- }
-
-
- public static void main(String[] args) {
-
- // 上传文件测试
- String str = uploadFile("http://localhost/MDM/upload.php",new String[] { "C:\\1.png" });
- System.out.println(str);
-
-
- }
-
- }
参考资料:
通过HttpURLConnection 上传文件_pois的博客-CSDN博客_httpurlconnection 文件上传
HttpUrlConnection上传文件_三木神奇的博客-CSDN博客_httpurlconnection 文件上传
4 参考资料
java实现调用http请求的几种常见方式_qq_duhai的博客-CSDN博客_java http
HttpUrlConnection上传文件_三木神奇的博客-CSDN博客_httpurlconnection 文件上传
通过HttpURLConnection 上传文件_pois的博客-CSDN博客_httpurlconnection 文件上传