JavaSE_URLConnection/HttpURLConnection发送HTTP请求的方法(一)
来源:互联网 发布:php手机短信验证 编辑:程序博客网 时间:2024/05/16 09:00
原文地址: https://www.cnblogs.com/h--d/p/5495524.html
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=我是谁")); }}
阅读全文
0 0
- JavaSE_URLConnection/HttpURLConnection发送HTTP请求的方法(一)
- httpURLConnection发送http请求
- 使用HttpURLConnection发送HTTP请求
- HttpURLConnection发送接收Http请求
- 使用httpurlconnection发送http请求
- Java 发送http请求 HttpURLConnection
- Android学习 (十六) 用HttpURLConnection方法发送一个HTTP请求
- 使用httpclient实现http链接池与使用HttpURLConnection发送http请求的方法与性能对比
- 如何发送HTTP请求之一:使用HttpURLConnection(入门篇)
- java-用HttpURLConnection发送Http请求.
- Android上使用HttpURLConnection发送HTTP请求
- Android使用HttpURLConnection发送HTTP请求
- 发送Http请求(POST GET)的方法
- 发送Http请求(POST GET)的方法
- 发送Http请求(POST GET)的方法
- 发送Http请求(POST GET)的方法
- 发送Http请求(POST GET)的方法
- 发送Http请求(POST GET)的方法
- [转载]理解OAuth 2.0
- 【Scikit-Learn 中文文档】广义线性模型
- C#获取本周/月第一天(后台)
- mybatis中大于等于小于等于的写法
- 动态规划之计算矩阵连乘积
- JavaSE_URLConnection/HttpURLConnection发送HTTP请求的方法(一)
- 开始写技术博客啦!
- python中的logging
- windows下如何快速优雅的使用python的科学计算库?
- 帮助企业做好MaxCompute大数据平台成本优化的最佳实践
- PHP面向对象
- 云平台直播对比小结
- Dagger2解耦简易版
- vue.js之render