封装 HttpURLConnection
HttpURLConnection为javaAPI提供的一种Rest访问的方式。其支持对Post,Delete,Get,Put等方式的访问。
以下为对于HttpURLConnection对Post等方式访问的一段代码。
- package com.sw.study.urlConnection;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.HashMap;
- import java.util.Map;
- public class URLConnectionUtil {
- private static final String SERVLET_POST = "POST" ;
- private static final String SERVLET_GET = "GET" ;
- private static final String SERVLET_DELETE = "DELETE" ;
- private static final String SERVLET_PUT = "PUT" ;
- private static String prepareParam(Map<String,Object> paramMap){
- StringBuffer sb = new StringBuffer();
- if (paramMap.isEmpty()){
- return "" ;
- }else {
- for (String key: paramMap.keySet()){
- String value = (String)paramMap.get(key);
- if (sb.length()< 1 ){
- sb.append(key).append("=" ).append(value);
- }else {
- sb.append("&" ).append(key).append( "=" ).append(value);
- }
- }
- return sb.toString();
- }
- }
- public static void doPost(String urlStr,Map<String,Object> paramMap ) throws Exception{
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod(SERVLET_POST);
- String paramStr = prepareParam(paramMap);
- conn.setDoInput(true );
- conn.setDoOutput(true );
- OutputStream os = conn.getOutputStream();
- os.write(paramStr.toString().getBytes("utf-8" ));
- os.close();
- BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream()));
- String line ;
- String result ="" ;
- while ( (line =br.readLine()) != null ){
- result += "/n" +line;
- }
- System.out.println(result);
- br.close();
- }
- public static void doGet(String urlStr,Map<String,Object> paramMap ) throws Exception{
- String paramStr = prepareParam(paramMap);
- if (paramStr == null || paramStr.trim().length()< 1 ){
- }else {
- urlStr +="?" +paramStr;
- }
- System.out.println(urlStr);
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod(SERVLET_PUT);
- conn.setRequestProperty("Content-Type" , "text/html; charset=UTF-8" );
- conn.connect();
- BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream()));
- String line ;
- String result ="" ;
- while ( (line =br.readLine()) != null ){
- result += "/n" +line;
- }
- System.out.println(result);
- br.close();
- }
- public static void doPut(String urlStr,Map<String,Object> paramMap) throws Exception{
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod(SERVLET_PUT);
- String paramStr = prepareParam(paramMap);
- conn.setDoInput(true );
- conn.setDoOutput(true );
- OutputStream os = conn.getOutputStream();
- os.write(paramStr.toString().getBytes("utf-8" ));
- os.close();
- BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream()));
- String line ;
- String result ="" ;
- while ( (line =br.readLine()) != null ){
- result += "/n" +line;
- }
- System.out.println(result);
- br.close();
- }
- public static void doDelete(String urlStr,Map<String,Object> paramMap) throws Exception{
- String paramStr = prepareParam(paramMap);
- if (paramStr == null || paramStr.trim().length()< 1 ){
- }else {
- urlStr +="?" +paramStr;
- }
- System.out.println(urlStr);
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setDoOutput(true );
- conn.setRequestMethod(SERVLET_DELETE);
- //屏蔽掉的代码是错误的,java.net.ProtocolException: HTTP method DELETE doesn't support output
- /* OutputStream os = conn.getOutputStream();
- os.write(paramStr.toString().getBytes("utf-8"));
- os.close(); */
- if (conn.getResponseCode() == 200 ){
- System.out.println("成功" );
- }else {
- System.out.println(conn.getResponseCode());
- }
- }
- public static void main(String[] args) throws Exception{
- String urlStr = "http://localhost:8080/SwTest/ReceiveDataServlet" ;
- Map<String,Object> map = new HashMap<String,Object>();
- map.put("username" , "张三" );
- map.put("password" , "88888" );
- // URLConnectionUtil.doGet(urlStr, map);
- // URLConnectionUtil.doPost(urlStr, map);
- // URLConnectionUtil.doPut(urlStr, map);
- URLConnectionUtil.doDelete(urlStr, map);
- }
- }
- package com.sw.study.urlConnection;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.HashMap;
- import java.util.Map;
- public class URLConnectionUtil {
- private static final String SERVLET_POST = "POST" ;
- private static final String SERVLET_GET = "GET" ;
- private static final String SERVLET_DELETE = "DELETE" ;
- private static final String SERVLET_PUT = "PUT" ;
- private static String prepareParam(Map<String,Object> paramMap){
- StringBuffer sb = new StringBuffer();
- if(paramMap.isEmpty()){
- return "" ;
- }else{
- for(String key: paramMap.keySet()){
- String value = (String)paramMap.get(key);
- if(sb.length()<1){
- sb.append(key).append("=").append(value);
- }else{
- sb.append("&").append(key).append("=").append(value);
- }
- }
- return sb.toString();
- }
- }
- public static void doPost(String urlStr,Map<String,Object> paramMap ) throws Exception{
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod(SERVLET_POST);
- String paramStr = prepareParam(paramMap);
- conn.setDoInput(true);
- conn.setDoOutput(true);
- OutputStream os = conn.getOutputStream();
- os.write(paramStr.toString().getBytes("utf-8"));
- os.close();
- BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String line ;
- String result ="";
- while( (line =br.readLine()) != null ){
- result += "/n"+line;
- }
- System.out.println(result);
- br.close();
- }
- public static void doGet(String urlStr,Map<String,Object> paramMap ) throws Exception{
- String paramStr = prepareParam(paramMap);
- if(paramStr == null || paramStr.trim().length()<1){
- }else{
- urlStr +="?"+paramStr;
- }
- System.out.println(urlStr);
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod(SERVLET_PUT);
- conn.setRequestProperty("Content-Type","text/html; charset=UTF-8");
- conn.connect();
- BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String line ;
- String result ="";
- while( (line =br.readLine()) != null ){
- result += "/n"+line;
- }
- System.out.println(result);
- br.close();
- }
- public static void doPut(String urlStr,Map<String,Object> paramMap) throws Exception{
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod(SERVLET_PUT);
- String paramStr = prepareParam(paramMap);
- conn.setDoInput(true);
- conn.setDoOutput(true);
- OutputStream os = conn.getOutputStream();
- os.write(paramStr.toString().getBytes("utf-8"));
- os.close();
- BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- String line ;
- String result ="";
- while( (line =br.readLine()) != null ){
- result += "/n"+line;
- }
- System.out.println(result);
- br.close();
- }
- public static void doDelete(String urlStr,Map<String,Object> paramMap) throws Exception{
- String paramStr = prepareParam(paramMap);
- if(paramStr == null || paramStr.trim().length()<1){
- }else{
- urlStr +="?"+paramStr;
- }
- System.out.println(urlStr);
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setDoOutput(true);
- conn.setRequestMethod(SERVLET_DELETE);
- //屏蔽掉的代码是错误的,java.net.ProtocolException: HTTP method DELETE doesn't support output
- /* OutputStream os = conn.getOutputStream();
- os.write(paramStr.toString().getBytes("utf-8"));
- os.close(); */
- if(conn.getResponseCode() ==200){
- System.out.println("成功");
- }else{
- System.out.println(conn.getResponseCode());
- }
- }
- public static void main(String[] args) throws Exception{
- String urlStr = "http://localhost:8080/SwTest/ReceiveDataServlet";
- Map<String,Object> map = new HashMap<String,Object>();
- map.put("username","张三");
- map.put("password","88888");
- // URLConnectionUtil.doGet(urlStr, map);
- // URLConnectionUtil.doPost(urlStr, map);
- // URLConnectionUtil.doPut(urlStr, map);
- URLConnectionUtil.doDelete(urlStr, map);
- }
- }
方法中是存在重复的。有些方法是可以通过参数的改变来达到统一,但是那样的做法对于程序的扩展性会有很大的局限性。
还是对于每一种方式提供一个单独的方法进行访问比较好。
在Servlet端,获取参数可以通过
request.getInputStream,及request.getParamter来进行。
其中,当Rest访问传入参数是通过conn的outputStream来进行的,可以通过request.getInputStream来进行参数获取(Post方式可通用);
当以url?key=value方法传递参数时,可以通过request.getParamter来进行参数获取。(Post方式可通用)
其中request.getInputStream和request.getParamter两种方式不能同时出现。当request.getParamter运行的过程,也是输入流的读取过程。当输入流读取完成后,再次调用时无效的。
附上Servlet端程序
- package com.sw.servlet;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import javax.servlet.ServletException;
- import javax.servlet.ServletInputStream;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * Servlet implementation class ReceiveDataServlet
- */
- public class ReceiveDataServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public ReceiveDataServlet() {
- super ();
- // TODO Auto-generated constructor stub
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- System.out.println("----------get--------------" );
- String username = new String(request.getParameter( "username" ).getBytes( "iso-8859-1" ), "utf-8" );
- String password = new String(request.getParameter( "password" ).getBytes( "iso-8859-1" ), "utf-8" );
- System.out.println(username);
- System.out.println(password);
- OutputStream os = response.getOutputStream();
- os.write("get" .getBytes( "utf-8" ));
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- System.out.println("----------post--------------" );
- BufferedReader br = new BufferedReader( new InputStreamReader((ServletInputStream)request.getInputStream()));
- String line = null ;
- StringBuilder sb = new StringBuilder();
- while ((line = br.readLine())!= null ){
- sb.append(line);
- }
- System.out.println(sb.toString());
- br.close();
- /* String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
- String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");
- System.out.println(username);
- System.out.println(password);
- */ OutputStream os = response.getOutputStream();
- os.write("post" .getBytes( "utf-8" ));
- }
- @Override
- protected void doDelete(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- System.out.println("----------delete--------------" );
- String username = new String(request.getParameter( "username" ).getBytes( "iso-8859-1" ), "utf-8" );
- String password = new String(request.getParameter( "password" ).getBytes( "iso-8859-1" ), "utf-8" );
- System.out.println(username);
- System.out.println(password);
- OutputStream os = response.getOutputStream();
- os.write("delete" .getBytes( "utf-8" ));
- }
- @Override
- protected void doPut(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- System.out.println("----------put--------------" );
- /* BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
- String line = null;
- StringBuilder sb = new StringBuilder();
- while((line = br.readLine())!=null){
- sb.append(line);
- }
- System.out.println(sb.toString());
- br.close();*/
- String username = new String(request.getParameter( "username" ).getBytes( "iso-8859-1" ), "utf-8" );
- String password = new String(request.getParameter( "password" ).getBytes( "iso-8859-1" ), "utf-8" );
- System.out.println(username);
- System.out.println(password);
- OutputStream os = response.getOutputStream();
- os.write("put" .getBytes( "utf-8" ));
- }
- }
- package com.sw.servlet;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import javax.servlet.ServletException;
- import javax.servlet.ServletInputStream;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- /**
- * Servlet implementation class ReceiveDataServlet
- */
- public class ReceiveDataServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public ReceiveDataServlet() {
- super();
- // TODO Auto-generated constructor stub
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- System.out.println("----------get--------------");
- String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
- String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");
- System.out.println(username);
- System.out.println(password);
- OutputStream os = response.getOutputStream();
- os.write("get".getBytes("utf-8"));
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
- */
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- System.out.println("----------post--------------");
- BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
- String line = null;
- StringBuilder sb = new StringBuilder();
- while((line = br.readLine())!=null){
- sb.append(line);
- }
- System.out.println(sb.toString());
- br.close();
- /* String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
- String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");
- System.out.println(username);
- System.out.println(password);
- */ OutputStream os = response.getOutputStream();
- os.write("post".getBytes("utf-8"));
- }
- @Override
- protected void doDelete(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- System.out.println("----------delete--------------");
- String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
- String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");
- System.out.println(username);
- System.out.println(password);
- OutputStream os = response.getOutputStream();
- os.write("delete".getBytes("utf-8"));
- }
- @Override
- protected void doPut(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- System.out.println("----------put--------------");
- /* BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
- String line = null;
- StringBuilder sb = new StringBuilder();
- while((line = br.readLine())!=null){
- sb.append(line);
- }
- System.out.println(sb.toString());
- br.close();*/
- String username = new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
- String password = new String(request.getParameter("password").getBytes("iso-8859-1"),"utf-8");
- System.out.println(username);
- System.out.println(password);
- OutputStream os = response.getOutputStream();
- os.write("put".getBytes("utf-8"));
- }
- }
程序中对于request.getInputStream和getParameter的获取方式可能说明的会多少有些问题,我也是通过几组测试后得出的结论。肯定有我没有测试到得。如果有问题,请指出,我会再看到评论后进行测试,修改。
另外,Apache的HttpClient非常好。封装的详细。在我的工作中也用到过,在以后会对于HttpClient进行有些单独的程序笔记。
这里HttpUrlConnection是同事在别的项目中用到的,用法比较简单,我大体给他简单讲解了一下,简明扼要,功能完备,还是很方便,
所以在这里记下来,留个笔记吧。
btw,最近工作比较忙,有2个月没有写些东西了,在工作中确实还遇到了不少有意思的问题,最近刚好快闲下来了,慢慢整理一下。