欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java利用java.net.URLConnection发送HTTP请求的方法详解

程序员文章站 2024-02-13 23:30:16
一、前言 如何通过java发送http请求,通俗点讲,如何通过java(模拟浏览器)发送http请求。 java有原生的api可用于发送http请求,即java.net...

一、前言

如何通过java发送http请求,通俗点讲,如何通过java(模拟浏览器)发送http请求。

java有原生的api可用于发送http请求,即java.net.urljava.net.urlconnection,这些api很好用、很常用,但不够简便;

所以,也流行有许多java http请求的framework,如,apache的httpclient。

目前项目主要用到java原生的方式,所以,这里主要介绍此方式。

二、运用原生java api发送简单的get请求、post请求步骤

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

       2.设置请求的参数

       3.发送请求

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

       5.关闭输入流

三、发送请求与接收响应流类 httprequestor

package me.http;

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.inetsocketaddress;
import java.net.proxy;
import java.net.url;
import java.net.urlconnection;
import java.util.iterator;
import java.util.map;

public class httprequestor {
 
 private string charset = "utf-8";
 private integer connecttimeout = null;
 private integer sockettimeout = null;
 private string proxyhost = null;
 private integer proxyport = null;
 
 /**
  * do get request
  * @param url
  * @return
  * @throws exception
  * @throws ioexception
  */
 public string doget(string url) throws exception {
  
  url localurl = new url(url);
  
  urlconnection connection = this.openconnection(localurl);
  httpurlconnection httpurlconnection = (httpurlconnection)connection;
  
  httpurlconnection.setrequestproperty("accept-charset", charset);
  httpurlconnection.setrequestproperty("content-type", "application/x-www-form-urlencoded");
  
  inputstream inputstream = null;
  inputstreamreader inputstreamreader = null;
  bufferedreader reader = null;
  stringbuffer resultbuffer = new stringbuffer();
  string templine = null;
  //响应失败
  if (httpurlconnection.getresponsecode() >= 300) {
   throw new exception("http request is not success, response code is " + httpurlconnection.getresponsecode());
  }
  
  try {
   inputstream = httpurlconnection.getinputstream();
   inputstreamreader = new inputstreamreader(inputstream);
   reader = new bufferedreader(inputstreamreader);
   
   while ((templine = reader.readline()) != null) {
    resultbuffer.append(templine);
   }
   
  } finally {
   
   if (reader != null) {
    reader.close();
   }
   
   if (inputstreamreader != null) {
    inputstreamreader.close();
   }
   
   if (inputstream != null) {
    inputstream.close();
   }
   
  }

  return resultbuffer.tostring();
 }
 
 /**
  * do post request
  * @param url
  * @param parametermap
  * @return
  * @throws exception 
  */
 public string dopost(string url, map parametermap) throws exception {
  
  /* translate parameter map to parameter date string */
  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("&");
    }
   }
  }
  
  system.out.println("post parameter : " + parameterbuffer.tostring());
  
  url localurl = new url(url);
  
  urlconnection connection = this.openconnection(localurl);
  httpurlconnection httpurlconnection = (httpurlconnection)connection;
  
  httpurlconnection.setdooutput(true);
  httpurlconnection.setrequestmethod("post");
  httpurlconnection.setrequestproperty("accept-charset", charset);
  httpurlconnection.setrequestproperty("content-type", "application/x-www-form-urlencoded");
  httpurlconnection.setrequestproperty("content-length", string.valueof(parameterbuffer.length()));
  
  outputstream outputstream = null;
  outputstreamwriter outputstreamwriter = null;
  inputstream inputstream = null;
  inputstreamreader inputstreamreader = null;
  bufferedreader reader = null;
  stringbuffer resultbuffer = new stringbuffer();
  string templine = null;
  
  try {
   outputstream = httpurlconnection.getoutputstream();
   outputstreamwriter = new outputstreamwriter(outputstream);
   
   outputstreamwriter.write(parameterbuffer.tostring());
   outputstreamwriter.flush();
   //响应失败
   if (httpurlconnection.getresponsecode() >= 300) {
    throw new exception("http request is not success, response code is " + httpurlconnection.getresponsecode());
   }
   //接收响应流
   inputstream = httpurlconnection.getinputstream();
   inputstreamreader = new inputstreamreader(inputstream);
   reader = new bufferedreader(inputstreamreader);
   
   while ((templine = reader.readline()) != null) {
    resultbuffer.append(templine);
   }
   
  } finally {
   
   if (outputstreamwriter != null) {
    outputstreamwriter.close();
   }
   
   if (outputstream != null) {
    outputstream.close();
   }
   
   if (reader != null) {
    reader.close();
   }
   
   if (inputstreamreader != null) {
    inputstreamreader.close();
   }
   
   if (inputstream != null) {
    inputstream.close();
   }
   
  }

  return resultbuffer.tostring();
 }

 private urlconnection openconnection(url localurl) throws ioexception {
  urlconnection connection;
  if (proxyhost != null && proxyport != null) {
   proxy proxy = new proxy(proxy.type.http, new inetsocketaddress(proxyhost, proxyport));
   connection = localurl.openconnection(proxy);
  } else {
   connection = localurl.openconnection();
  }
  return connection;
 }
 
 /**
  * render request according setting
  * @param request
  */
 private void renderrequest(urlconnection connection) {
  
  if (connecttimeout != null) {
   connection.setconnecttimeout(connecttimeout);
  }
  
  if (sockettimeout != null) {
   connection.setreadtimeout(sockettimeout);
  }
  
 }

 /*
  * getter & setter
  */
 public integer getconnecttimeout() {
  return connecttimeout;
 }

 public void setconnecttimeout(integer connecttimeout) {
  this.connecttimeout = connecttimeout;
 }

 public integer getsockettimeout() {
  return sockettimeout;
 }

 public void setsockettimeout(integer sockettimeout) {
  this.sockettimeout = sockettimeout;
 }

 public string getproxyhost() {
  return proxyhost;
 }

 public void setproxyhost(string proxyhost) {
  this.proxyhost = proxyhost;
 }

 public integer getproxyport() {
  return proxyport;
 }

 public void setproxyport(integer proxyport) {
  this.proxyport = proxyport;
 }

 public string getcharset() {
  return charset;
 }

 public void setcharset(string charset) {
  this.charset = charset;
 }
 
}

四、为测试方便,新建一个项目,并新建一个servlet,接收post请求并对httprequestor请求响应,发出响应流

java利用java.net.URLConnection发送HTTP请求的方法详解

loginservlet.java代码:此处使用了

注解: @webservlet("/loginservlet") ,也可以在web.xml配置servlet

package me.loginservlet;

import java.io.ioexception;
import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

/**
 * servlet implementation class loginservlet
 */
@webservlet("/loginservlet")
public class loginservlet extends httpservlet {
 private static final long serialversionuid = 1l;
  
 /**
  * @see httpservlet#httpservlet()
  */
 public loginservlet() {
  super();
  // todo auto-generated constructor stub
 }

 /**
  * @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
  */
 protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  // todo auto-generated method stub
  system.out.println("111");
 }

 /**
  * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)
  */
 protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  // todo auto-generated method stub
   string username = request.getparameter("username");
   string blog = request.getparameter("blog");
   
   system.out.println(username);
   system.out.println(blog);
   
   response.setcontenttype("text/plain; charset=utf-8");
   response.setcharacterencoding("utf-8");
//响应流
   response.getwriter().write("it is ok!");
  
 }

}

五.测试类test.java

package me.http;

import java.util.hashmap;
import java.util.map;

public class test {
public static void main(string[] args) {
  /* post request */
 map datamap = new hashmap();
 datamap.put("username", "nick huang");
 datamap.put("blog", "it");
 try {
  system.out.println(new httprequestor().dopost("http://localhost:8081/testprogect2/loginservlet", datamap));
  //system.out.println(new httprequestor().doget("http://localhost:8081/testprogect2/loginservlet"));
 } catch (exception e) {
  // todo auto-generated catch block
  e.printstacktrace();
 }
 
 /* get request */
 
}
}

1.接收post请求类loginservlet,控制台测试结果

java利用java.net.URLConnection发送HTTP请求的方法详解

2.httprequestor接收loginservlet返回的流

java利用java.net.URLConnection发送HTTP请求的方法详解

ok,完成

六.对于接收testprogect2项目中loginservlet.java类返回的流,在真实环境中可能是异步接收返回的流的,当一台机器a向另外一台机器b发送请求,b接收到a的信息,将信息处理后,需要将处理结果返回即响应返回给a,a会接收到b返回的信息

可以另外建一个servlet类httplistenerservlet.java来专门异步接收返回的信息

package me.http;

import java.io.bufferedreader;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;

import javax.servlet.servletexception;
import javax.servlet.annotation.webservlet;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

/**
 * servlet implementation class httplistenerservlet
 */
@webservlet("/httplistenerservlet")
public class httplistenerservlet extends httpservlet {
 private static final long serialversionuid = 1l;
  
 /**
  * @see httpservlet#httpservlet()
  */
 public httplistenerservlet() {
  super();
  // todo auto-generated constructor stub
 }

 /**
  * @see httpservlet#doget(httpservletrequest request, httpservletresponse response)
  */
 protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  // todo auto-generated method stub
 }

 /**
  * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)
  */
 protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
  // todo auto-generated method stub
   inputstream inputstream = null;
   inputstream = request.getinputstream();
   inputstreamreader inputstreamreader = new inputstreamreader(inputstream);
   bufferedreader reader = new bufferedreader(inputstreamreader);
   string templine = null;
   stringbuffer resultbuffer=new stringbuffer();
   while ((templine = reader.readline()) != null) {
    resultbuffer.append(templine);
   }
   
   system.out.println(resultbuffer.tostring());
 }

}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。