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

URLConnection发送HTTP请求的方法_动力节点Java学院整理

程序员文章站 2023-11-30 12:22:16
如何通过java发送http请求,通俗点讲,如何通过java(模拟浏览器)发送http请求。 java有原生的api可用于发送http请求,即java.net.url...

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

java有原生的api可用于发送http请求,即java.net.url、java.net.urlconnection,这些api很好用、很常用,但不够简便;
所以,也流行有许多java http请求的framework,如,apache的httpclient。

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

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

http请求粗分为两种,一种是get请求,一种是post请求。使用java发送这两种请求的代码大同小异,只是一些参数设置的不同。步骤如下:

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

2.设置请求的参数

3.发送请求

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

5.关闭输入流

简单的get请求示例如下:

package com.bjpowernode.httprequestdemo;

import java.io.bufferedreader;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.net.httpurlconnection;
import java.net.url;
import java.net.urlconnection;

public class httpgetrequest {

  /**
   * main
   * @param args
   * @throws exception 
   */
  public static void main(string[] args) throws exception {
    system.out.println(doget());
  }
  
  /**
   * get request
   * @return
   * @throws exception
   */
  public static string doget() throws exception {
    url localurl = new url("http://localhost:8080/onehttpserver/");
    urlconnection connection = localurl.openconnection();
    httpurlconnection httpurlconnection = (httpurlconnection)connection;
    
    httpurlconnection.setrequestproperty("accept-charset", "utf-8");
    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();
  }
  
}

 简单的post请求示例如下:

package com.bjpowernode.httprequestdemo;

import java.io.bufferedreader;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.io.outputstreamwriter;
import java.net.httpurlconnection;
import java.net.url;
import java.net.urlconnection;

public class httppostrequest {

  /**
   * main
   * @param args
   * @throws exception 
   */
  public static void main(string[] args) throws exception {
    system.out.println(dopost());
  }
  
  /**
   * post request
   * @return
   * @throws exception
   */
  public static string dopost() throws exception {
    string parameterdata = "username=nickhuang&blog=http://www.cnblogs.com/nick-huang/";
    
    url localurl = new url("http://localhost:8080/onehttpserver/");
    urlconnection connection = localurl.openconnection();
    httpurlconnection httpurlconnection = (httpurlconnection)connection;
    
    httpurlconnection.setdooutput(true);
    httpurlconnection.setrequestmethod("post");
    httpurlconnection.setrequestproperty("accept-charset", "utf-8");
    httpurlconnection.setrequestproperty("content-type", "application/x-www-form-urlencoded");
    httpurlconnection.setrequestproperty("content-length", string.valueof(parameterdata.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(parameterdata.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();
  }

}

简单封装

如果项目中有多处地方使用http请求,我们适当对其进行封装,

  1. 可以大大减少代码量(不需每次都写一大段原生的请求source code)
  2. 也可以使配置更灵活、方便(全局设置一些项目特有的配置,比如已商榷的time out时间、已确定的proxy server,避免以后改动繁琐)

 以下简单封装成httprequestor,以便使用:

package com.bjpowernode.util.httprequestor;

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 = 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 = 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;
  }
  
}

写一个调用的测试类:

package com.bjpowernode.util.httprequestor;

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

public class call {

  public static void main(string[] args) throws exception {
    
    /* post request */
    map datamap = new hashmap();
    datamap.put("username", "nick huang");
    datamap.put("blog", "it");
    system.out.println(new httprequestor().dopost("http://localhost:8080/onehttpserver/", datamap));
    
    /* get request */
    system.out.println(new httprequestor().doget("http://localhost:8080/onehttpserver/"));
  }

}

ok,完成!!

简单测试

以上的请求地址都是http://localhost:8080/onehttpserver/

这是自己的一个用于测试的web application,就一个简单的servlet和web.xml。毕竟需要测试请求参数是否能正常接收,处理超时的情况。

loginservlet

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 loginservlet extends httpservlet {
  private static final long serialversionuid = 1l;
    
  public loginservlet() {
    super();
  }

  protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    this.dopost(request, response);
  }

  protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
    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!");
  }

}

 web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="webapp_id" version="2.5">
 <display-name>onehttpserver</display-name>
 <welcome-file-list>
  <welcome-file>loginservlet</welcome-file>
 </welcome-file-list>
 
 <servlet>
  <description></description>
  <display-name>loginservlet</display-name>
  <servlet-name>loginservlet</servlet-name>
  <servlet-class>loginservlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>loginservlet</servlet-name>
  <url-pattern>/loginservlet</url-pattern>
 </servlet-mapping>
 
</web-app>