Java原生的API可用于发送HTTP请求

即java.net.URL、java.net.URLConnection,JDK自带的类;

1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)

2.设置请求的参数

3.发送请求

4.以输入流的形式获取返回内容

5.关闭输入流

  • 封装请求类

     package com.util;
    
     import java.io.BufferedReader;
    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; public class HttpConnectionUtil { // post请求
    public static final String HTTP_POST = "POST"; // get请求
    public static final String HTTP_GET = "GET"; // utf-8字符编码
    public static final String CHARSET_UTF_8 = "utf-8"; // HTTP内容类型。如果未指定ContentType,默认为TEXT/HTML
    public static final String CONTENT_TYPE_TEXT_HTML = "text/xml"; // HTTP内容类型。相当于form表单的形式,提交暑假
    public static final String CONTENT_TYPE_FORM_URL = "application/x-www-form-urlencoded"; // 请求超时时间
    public static final int SEND_REQUEST_TIME_OUT = 50000; // 将读超时时间
    public static final int READ_TIME_OUT = 50000; /**
    *
    * @param requestType
    * 请求类型
    * @param urlStr
    * 请求地址
    * @param body
    * 请求发送内容
    * @return 返回内容
    */
    public static String requestMethod(String requestType, String urlStr, String body) { // 是否有http正文提交
    boolean isDoInput = false;
    if (body != null && body.length() > 0)
    isDoInput = true;
    OutputStream outputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader = null;
    StringBuffer resultBuffer = new StringBuffer();
    String tempLine = null;
    try {
    // 统一资源
    URL url = new URL(urlStr);
    // 连接类的父类,抽象类
    URLConnection urlConnection = url.openConnection();
    // http的连接类
    HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
    // http正文内,因此需要设为true, 默认情况下是false;
    if (isDoInput) {
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestProperty("Content-Length", String.valueOf(body.length()));
    }
    // 设置是否从httpUrlConnection读入,默认情况下是true;
    httpURLConnection.setDoInput(true);
    // 设置一个指定的超时值(以毫秒为单位)
    httpURLConnection.setConnectTimeout(SEND_REQUEST_TIME_OUT);
    // 将读超时设置为指定的超时,以毫秒为单位。
    httpURLConnection.setReadTimeout(READ_TIME_OUT);
    // Post 请求不能使用缓存
    httpURLConnection.setUseCaches(false);
    // 设置字符编码
    httpURLConnection.setRequestProperty("Accept-Charset", CHARSET_UTF_8);
    // 设置内容类型
    httpURLConnection.setRequestProperty("Content-Type", CONTENT_TYPE_FORM_URL);
    // 设定请求的方法,默认是GET
    httpURLConnection.setRequestMethod(requestType); // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
    // 如果在已打开连接(此时 connected 字段的值为 true)的情况下调用 connect 方法,则忽略该调用。
    httpURLConnection.connect(); if (isDoInput) {
    outputStream = httpURLConnection.getOutputStream();
    outputStreamWriter = new OutputStreamWriter(outputStream);
    outputStreamWriter.write(body);
    outputStreamWriter.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); while ((tempLine = reader.readLine()) != null) {
    resultBuffer.append(tempLine);
    resultBuffer.append("\n");
    }
    } } catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally {// 关闭流 try {
    if (outputStreamWriter != null) {
    outputStreamWriter.close();
    }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    try {
    if (outputStream != null) {
    outputStream.close();
    }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    try {
    if (reader != null) {
    reader.close();
    }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    try {
    if (inputStreamReader != null) {
    inputStreamReader.close();
    }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    try {
    if (inputStream != null) {
    inputStream.close();
    }
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    return resultBuffer.toString();
    } /**
    * 将map集合的键值对转化成:key1=value1&key2=value2 的形式
    *
    * @param parameterMap
    * 需要转化的键值对集合
    * @return 字符串
    */
    public static String convertStringParamter(Map parameterMap) {
    StringBuffer parameterBuffer = new StringBuffer();
    if (parameterMap != null) {
    Iterator iterator = parameterMap.keySet().iterator();
    String key = null;
    String value = null;
    while (iterator.hasNext()) {
    key = (String) iterator.next();
    if (parameterMap.get(key) != null) {
    value = (String) parameterMap.get(key);
    } else {
    value = "";
    }
    parameterBuffer.append(key).append("=").append(value);
    if (iterator.hasNext()) {
    parameterBuffer.append("&");
    }
    }
    }
    return parameterBuffer.toString();
    } public static void main(String[] args) throws MalformedURLException { System.out.println(requestMethod(HTTP_GET, "http://127.0.0.1:8080/test/TestHttpRequestServlet",
    "username=123&password=我是谁")); }
    }

    HttpConnectionUtil

  • 测试Servlet

     package com.servlet;
    
     import java.io.IOException;
    
     import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse; public class TestHttpRequestServelt extends HttpServlet { @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("this is a TestHttpRequestServlet");
    request.setCharacterEncoding("utf-8"); String username = request.getParameter("username");
    String password = request.getParameter("password"); System.out.println(username);
    System.out.println(password); response.setContentType("text/plain; charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write("This is ok!"); }
    }

    TestHttpRequestServelt

  • web.xml配置

     <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
    <display-name>test</display-name> <servlet>
    <servlet-name>TestHttpRequestServlet</servlet-name>
    <servlet-class>com.servlet.TestHttpRequestServelt</servlet-class>
    </servlet> <servlet-mapping>
    <servlet-name>TestHttpRequestServlet</servlet-name>
    <url-pattern>/TestHttpRequestServlet</url-pattern>
    </servlet-mapping> <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    </web-app>

    web.xml

【JAVA】通过URLConnection/HttpURLConnection发送HTTP请求的方法(一)的更多相关文章

  1. Java利用原始HttpURLConnection发送http请求数据小结

    1,在post请求下,写输出应该在读取之后,否则会抛出异常. 即操作OutputStream对象应该在InputStreamReader之前. 2.conn.getResponseCode()获取返回 ...

  2. 【JAVA】通过HttpClient发送HTTP请求的方法

    HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 ...

  3. HttpURLConnection发送POST请求(可包含文件)

    import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io. ...

  4. 谈谈Java利用原始HttpURLConnection发送POST数据

    这篇文章主要给大家介绍java利用原始httpUrlConnection发送post数据,设计到httpUrlConnection类的相关知识,感兴趣的朋友跟着小编一起学习吧 URLConnectio ...

  5. java 常见几种发送http请求案例

    import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java ...

  6. HttpURLConnection 发送http请求帮助类

    java 利用HttpURLConnection 发送http请求 提供GET / POST /上传文件/下载文件 功能 import java.io.*; import java.net.*; im ...

  7. java中发送http请求的方法

    package org.jeecgframework.test.demo; import java.io.BufferedReader; import java.io.FileOutputStream ...

  8. HttpUrlConnection发送url请求(后台springmvc)

    1.HttpURLConnection发送url请求 public class JavaRequest { private static final String BASE_URL = "h ...

  9. 发送http请求的方法

    在http/1.1 协议中,定义了8种发送http请求的方法 get post options head put delete trace connect patch. 根据http协议的设计初衷,不 ...

随机推荐

  1. 64位win10系统无法安装.Net framework3.5的两种解决方法

    参考网站: https://blog.csdn.net/zang141588761/article/details/52177290 在Windows10中,当我们安装某些软件的时候会提示“你的电脑上 ...

  2. hive 上篇

    hive 是以hadoop为基础的数据仓库,使用HQL查询存放在HDFS上面的数据,HSQL是一种类SQL的语句,最终会被编译成map/reduce,HSQL可以查询HDFS上面的数据:不支持记录级别 ...

  3. C#_Markov_心得感想

    来到实验室正好有一个月了,趁着端午假期稍微轻松一些,在大改程序体系之前,想将自己在这30天中工作之一Markov回顾一下,将从真实的写程序中学习到的知识.思想记录下来.希望能和大家积极讨论! 本文会以 ...

  4. [python爬虫] Selenium定向爬取PubMed生物医学摘要信息

    本文主要是自己的在线代码笔记.在生物医学本体Ontology构建过程中,我使用Selenium定向爬取生物医学PubMed数据库的内容.        PubMed是一个免费的搜寻引擎,提供生物医学方 ...

  5. 树结构之JavaScript

    对于数据结构“树”,想必大家都熟悉,今儿,我们就再来回顾一下数据结构中的二叉树与树,并用JavaScript实现它们. ps:树结构在前端中,很多地方体现得淋漓尽致,如Vue的虚拟DOM以及冒泡等等. ...

  6. JS实现让滚轮控制网页头部显示与隐藏

    在很多网站中都有鼠标网上滚动头部就会滑出,继续往下滚动就会隐藏,下面看看实现方法 scroll(); function scroll(){// 入口方法 这个方法是获取事件的兼容,获取delta -- ...

  7. Win7 系统还原

    Win7 由于某种原因,第二天开机不正常,桌面配置丢失,桌面上的文档不见了. 这种情况不要怕. 可以在启动界面F8,进入系统还原,然后选择某个时间点还原成功!!! 错误描述: Windows 不能加载 ...

  8. PPT怎么母版怎么修改及应用

    打开一个PPT,假设我要建一个母版(目的就是母版容易全部修改,不用同样的内容一个一个改) 然后点击如图"视图"+"幻灯片母版" 然后就会出现一个这样的工具栏界面 ...

  9. Spring mvc RequestContextHolder分析

    转载: http://blog.csdn.net/zzy7075/article/details/53559902

  10. linux系统安装中文支持,解决中文乱码问题

    怎么设置Linux系统中文语言,这是很多小伙伴在开始使用Linux的时候,都会遇到一个问题,就是终端输入命令回显的时候中文显示乱码.出现这个情况一般是由于没有安装中文语言包,或者设置的默认语言有问题导 ...