`

通过java.net.URLConnection发送HTTP请求

阅读更多

        如何通过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请求。(详细的请见:Hypertext Transfer Protocol -- HTTP/1.1 - Method Definitions

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

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

        2.设置请求的参数

        3.发送请求

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

        5.关闭输入流

        简单的Get请求示例如下:

package com.bijian.study;

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 {

	public static void main(String[] args) throws Exception {
		System.out.println(doGet());
	}

	/**
	 * Get Request
	 * @throws Exception
	 */
	public static String doGet() throws Exception {
		
		URL localURL = new URL("http://localhost:8080/SpringMVC/greeting?name=zhangshan");
		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.bijian.study;

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 {

    public static void main(String[] args) throws Exception {
        System.out.println(doPost());
    }
    
    /**
     * Post Request
     * @throws Exception
     */
    public static String doPost() throws Exception {
    	
        String parameterData = "name=zhangshan";
        
        URL localURL = new URL("http://localhost:8080/SpringMVC/greeting");
        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请求,我们适当对其进行封装,可以大大减少代码量(不需每次都写一大段原生的请求Source code),也可以使配置更灵活、方便(全局设置一些项目特有的配置,比如已商榷的time out时间、已确定的Proxy Server,避免以后改动繁琐)。

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

package com.bijian.study;

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.bijian.study;

import java.util.HashMap;
import java.util.Map;

public class HttpRequestorTest {

	public static void main(String[] args) throws Exception {

		/* Post Request */
		Map dataMap = new HashMap();
		dataMap.put("name", "zhangshan");
		System.out.println(new HttpRequestor().doPost("http://localhost:8080/SpringMVC/greeting", dataMap));
		
		/* Get Request */
		System.out.println(new HttpRequestor().doGet("http://localhost:8080/SpringMVC/greeting?name=zhangshan"));
	}
}

        OK,完成!!

 

PS:以上的请求地址都是http://localhost:8080/SpringMVC/greeting,这是自己的一个用于测试的Web Application,详见附件,如想进一步了解Web Application,请参考http://bijian1013.iteye.com/blog/2166539

 

文章来源:http://www.cnblogs.com/nick-huang/p/3859353.html

分享到:
评论

相关推荐

    java.net.URLConnection发送HTTP请求与通过Apache HttpClient发送HTTP请求比较

    有两种常见的方法:一是使用`java.net.URLConnection`类,二是通过Apache HttpClient库。这篇文章将对比这两种方法,探讨它们的优缺点以及适用场景。 `java.net.URLConnection`是Java标准库中的一个类,可以直接...

    java如何利用java.net.URLConnection发送HTTP.docx

    以下是如何利用`java.net.URLConnection`发送HTTP请求的详细步骤: 1. **创建URL对象**: 首先,你需要创建一个`java.net.URL`对象,它代表了你要访问的网络资源的地址。例如: ```java URL url = new URL(...

    java.net.URL测试代码

    通过以上步骤,你可以完成一个基本的基于`java.net.URL`和`URLConnection`的网络请求。在实际开发中,考虑到易用性、异常处理和重试机制,往往会选择使用更高级的HTTP客户端库,如Apache HttpClient或OkHttp,它们...

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

    本文将详细介绍如何使用`java.net.URLConnection`来实现这一功能。`URLConnection`是Java标准库中的一个核心类,它允许我们与各种协议(包括HTTP)的URL进行交互。 一、Java原生API发送HTTP请求 1. **创建URL对象*...

    java中用URLConnection_类post方式提交表单

    java中用URLConnection类post方式提交表单是指在java应用程序中使用java.net.URLConnection类来实现POST方式的表单提交。POST方式是HTTP协议中的一种常见的请求方法,它允许客户端向服务器发送数据。下面是使用...

    coke-very-the.rar_Coke

    3. URLConnection.java:`java.net.URLConnection`是所有Java URL连接类的基类,负责建立到URL指定的资源的连接。你可以通过它发送请求、接收响应,进行读写操作。 4. Socket.java:`java.net.Socket`是TCP/IP网络...

    基础深化和提高-网络编程

    HTTP客户端:Java提供了java.net.HttpURLConnection等类,用于创建HTTP客户端并进行HTTP请求和响应的处理。 RMI(远程方法调用):Java的远程方法调用技术允许在不同的JVM(Java虚拟机)上执行方法调用,使得分布在...

    java程序设计之网络编程学习课件

    3. **URL与URLConnection**:`java.net.URL`类用于表示统一资源定位符,`java.net.URLConnection`则用于打开和操作与URL关联的连接。它们简化了HTTP、FTP等协议的访问。 4. **NIO(非阻塞I/O)**:Java 1.4引入了`...

    java调用WebService(客户端)宣贯.pdf

    在Java中,你可以使用`java.net.URL`和`java.net.URLConnection`类来实现GET请求。 2.HttpPost调用: HttpPost方式在HTTP请求的正文中传递参数,如`name1=value1&name2=value2...`。返回的响应同样是一个无`...

    Java-Java网络编程教程

    Java标准库提供了`java.net.HttpURLConnection`来发送HTTP请求,但实际开发中,我们常常会使用第三方库,如Apache HttpClient或OkHttp,它们提供了更强大的功能和易用性。 七、HTTPS安全通信 在处理敏感数据时,...

    JavaHTTP协议实现

    在Java中,我们可以使用`java.net.URL`和`java.net.URLConnection`类来实现GET请求。以下是一个简单的示例,展示了如何使用GET方法下载服务器上的图片: ```java import java.io.InputStream; import java.net.URL;...

    使用JAVA原生实现简单的HTTP请求

    在Java编程语言中,发送HTTP请求是常见的网络通信任务,主要用到的是`java.net.URL`和`java.net.HttpURLConnection`这两个核心类。本篇将详细介绍如何使用Java原生API实现简单的HTTP请求。 首先,我们需要了解HTTP...

    java访问网络资源

    在Java中,访问网络资源是通过标准的Java API实现的,其中`java.net.URL`类和`java.net.URLConnection`类扮演了核心角色。本文将深入探讨这两个类以及如何使用它们来实现Java与服务器之间的数据交互。 首先,`java...

    Java从网络取得图像源码

    在Java中,我们可以使用`java.net.URL`和`java.net.URLConnection`类来发起HTTP请求。 下面是一段简单的示例代码,演示了如何从网络下载一个图像文件: ```java import java.io.InputStream; import java.net.URL;...

    向URL发送请求

    3. `HttpClient`(Java 11+):从Java 11开始,内置了`java.net.http.HttpClient`,提供了一个现代、异步、高性能的API来处理HTTP请求。它支持同步和异步操作,简化了网络请求的编写。 ```java HttpClient client =...

    常用的免费接口

    import java.net.URLConnection; public class Test { public static void main(String[] args) { String st = "北京"; String str = catchPage("http://api.liqwei.com/weather/?city=+" + st + "+"); ...

    java使用url发送post和get请求:HttpConnUtils.jar

    - 在`HttpConnUtils`中,可能有一个`sendGetRequest()`方法,接受URL和参数,将参数编码并添加到URL路径,然后使用`java.net.HttpURLConnection`或`java.net.URLConnection`来建立连接并读取响应。 2. **HTTP POST...

Global site tag (gtag.js) - Google Analytics