`
tiwson
  • 浏览: 333020 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

JAVA发送HTTP请求,并接受返回内容

阅读更多
JDK 中提供了一些对无状态协议请求(HTTP )的支持,下面我就将我所写的一个小例子(组件)进行描述:

首先让我们先构建一个请求类(HttpRequester )。

该类封装了 JAVA 实现简单请求的代码,如下:


Java代码
import java.io.BufferedReader;   
import java.io.IOException;   
import java.io.InputStream;   
import java.io.InputStreamReader;   
import java.net.HttpURLConnection;   
import java.net.URL;   
import java.nio.charset.Charset;   
import java.util.Map;   
import java.util.Vector;   
    
/**  
 * HTTP请求对象  
 *   
 * @author YYmmiinngg  
 */  
public class HttpRequester {   
    private String defaultContentEncoding;   
    
    public HttpRequester() {   
        this.defaultContentEncoding = Charset.defaultCharset().name();   
    }   
    
    /**  
     * 发送GET请求  
     *   
     * @param urlString  
     *            URL地址  
     * @return 响应对象  
     * @throws IOException  
     */  
    public HttpRespons sendGet(String urlString) throws IOException {   
        return this.send(urlString, "GET", null, null);   
    }   
    
    /**  
     * 发送GET请求  
     *   
     * @param urlString  
     *            URL地址  
     * @param params  
     *            参数集合  
     * @return 响应对象  
     * @throws IOException  
     */  
    public HttpRespons sendGet(String urlString, Map<String, String> params)   
            throws IOException {   
        return this.send(urlString, "GET", params, null);   
    }   
    
    /**  
     * 发送GET请求  
     *   
     * @param urlString  
     *            URL地址  
     * @param params  
     *            参数集合  
     * @param propertys  
     *            请求属性  
     * @return 响应对象  
     * @throws IOException  
     */  
    public HttpRespons sendGet(String urlString, Map<String, String> params,   
            Map<String, String> propertys) throws IOException {   
        return this.send(urlString, "GET", params, propertys);   
    }   
    
    /**  
     * 发送POST请求  
     *   
     * @param urlString  
     *            URL地址  
     * @return 响应对象  
     * @throws IOException  
     */  
    public HttpRespons sendPost(String urlString) throws IOException {   
        return this.send(urlString, "POST", null, null);   
    }   
    
    /**  
     * 发送POST请求  
     *   
     * @param urlString  
     *            URL地址  
     * @param params  
     *            参数集合  
     * @return 响应对象  
     * @throws IOException  
     */  
    public HttpRespons sendPost(String urlString, Map<String, String> params)   
            throws IOException {   
        return this.send(urlString, "POST", params, null);   
    }   
    
    /**  
     * 发送POST请求  
     *   
     * @param urlString  
     *            URL地址  
     * @param params  
     *            参数集合  
     * @param propertys  
     *            请求属性  
     * @return 响应对象  
     * @throws IOException  
     */  
    public HttpRespons sendPost(String urlString, Map<String, String> params,   
            Map<String, String> propertys) throws IOException {   
        return this.send(urlString, "POST", params, propertys);   
    }   
    
    /**  
     * 发送HTTP请求  
     *   
     * @param urlString  
     * @return 响映对象  
     * @throws IOException  
     */  
    private HttpRespons send(String urlString, String method,   
            Map<String, String> parameters, Map<String, String> propertys)   
            throws IOException {   
        HttpURLConnection urlConnection = null;   
    
        if (method.equalsIgnoreCase("GET") && parameters != null) {   
            StringBuffer param = new StringBuffer();   
            int i = 0;   
            for (String key : parameters.keySet()) {   
                if (i == 0)   
                    param.append("?");   
                else  
                    param.append("&");   
                param.append(key).append("=").append(parameters.get(key));   
                i++;   
            }   
            urlString += param;   
        }   
        URL url = new URL(urlString);   
        urlConnection = (HttpURLConnection) url.openConnection();   
    
        urlConnection.setRequestMethod(method);   
        urlConnection.setDoOutput(true);   
        urlConnection.setDoInput(true);   
        urlConnection.setUseCaches(false);   
    
        if (propertys != null)   
            for (String key : propertys.keySet()) {   
                urlConnection.addRequestProperty(key, propertys.get(key));   
            }   
    
        if (method.equalsIgnoreCase("POST") && parameters != null) {   
            StringBuffer param = new StringBuffer();   
            for (String key : parameters.keySet()) {   
                param.append("&");   
                param.append(key).append("=").append(parameters.get(key));   
            }   
            urlConnection.getOutputStream().write(param.toString().getBytes());   
            urlConnection.getOutputStream().flush();   
            urlConnection.getOutputStream().close();   
        }   
    
        return this.makeContent(urlString, urlConnection);   
    }   
    
    /**  
     * 得到响应对象  
     *   
     * @param urlConnection  
     * @return 响应对象  
     * @throws IOException  
     */  
    private HttpRespons makeContent(String urlString,   
            HttpURLConnection urlConnection) throws IOException {   
        HttpRespons httpResponser = new HttpRespons();   
        try {   
            InputStream in = urlConnection.getInputStream();   
            BufferedReader bufferedReader = new BufferedReader(   
                    new InputStreamReader(in));   
            httpResponser.contentCollection = new Vector<String>();   
            StringBuffer temp = new StringBuffer();   
            String line = bufferedReader.readLine();   
            while (line != null) {   
                httpResponser.contentCollection.add(line);   
                temp.append(line).append("\r\n");   
                line = bufferedReader.readLine();   
            }   
            bufferedReader.close();   
    
            String ecod = urlConnection.getContentEncoding();   
            if (ecod == null)   
                ecod = this.defaultContentEncoding;   
    
            httpResponser.urlString = urlString;   
    
            httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();   
            httpResponser.file = urlConnection.getURL().getFile();   
            httpResponser.host = urlConnection.getURL().getHost();   
            httpResponser.path = urlConnection.getURL().getPath();   
            httpResponser.port = urlConnection.getURL().getPort();   
            httpResponser.protocol = urlConnection.getURL().getProtocol();   
            httpResponser.query = urlConnection.getURL().getQuery();   
            httpResponser.ref = urlConnection.getURL().getRef();   
            httpResponser.userInfo = urlConnection.getURL().getUserInfo();   
    
            httpResponser.content = new String(temp.toString().getBytes(), ecod);   
            httpResponser.contentEncoding = ecod;   
            httpResponser.code = urlConnection.getResponseCode();   
            httpResponser.message = urlConnection.getResponseMessage();   
            httpResponser.contentType = urlConnection.getContentType();   
            httpResponser.method = urlConnection.getRequestMethod();   
            httpResponser.connectTimeout = urlConnection.getConnectTimeout();   
            httpResponser.readTimeout = urlConnection.getReadTimeout();   
    
            return httpResponser;   
        } catch (IOException e) {   
            throw e;   
        } finally {   
            if (urlConnection != null)   
                urlConnection.disconnect();   
        }   
    }   
    
    /**  
     * 默认的响应字符集  
     */  
    public String getDefaultContentEncoding() {   
        return this.defaultContentEncoding;   
    }   
    
    /**  
     * 设置默认的响应字符集  
     */  
    public void setDefaultContentEncoding(String defaultContentEncoding) {   
        this.defaultContentEncoding = defaultContentEncoding;   
    }   
}  

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Vector;
 
/**
 * HTTP请求对象
 * 
 * @author YYmmiinngg
 */
public class HttpRequester {
	private String defaultContentEncoding;
 
	public HttpRequester() {
		this.defaultContentEncoding = Charset.defaultCharset().name();
	}
 
	/**
	 * 发送GET请求
	 * 
	 * @param urlString
	 *            URL地址
	 * @return 响应对象
	 * @throws IOException
	 */
	public HttpRespons sendGet(String urlString) throws IOException {
		return this.send(urlString, "GET", null, null);
	}
 
	/**
	 * 发送GET请求
	 * 
	 * @param urlString
	 *            URL地址
	 * @param params
	 *            参数集合
	 * @return 响应对象
	 * @throws IOException
	 */
	public HttpRespons sendGet(String urlString, Map<String, String> params)
			throws IOException {
		return this.send(urlString, "GET", params, null);
	}
 
	/**
	 * 发送GET请求
	 * 
	 * @param urlString
	 *            URL地址
	 * @param params
	 *            参数集合
	 * @param propertys
	 *            请求属性
	 * @return 响应对象
	 * @throws IOException
	 */
	public HttpRespons sendGet(String urlString, Map<String, String> params,
			Map<String, String> propertys) throws IOException {
		return this.send(urlString, "GET", params, propertys);
	}
 
	/**
	 * 发送POST请求
	 * 
	 * @param urlString
	 *            URL地址
	 * @return 响应对象
	 * @throws IOException
	 */
	public HttpRespons sendPost(String urlString) throws IOException {
		return this.send(urlString, "POST", null, null);
	}
 
	/**
	 * 发送POST请求
	 * 
	 * @param urlString
	 *            URL地址
	 * @param params
	 *            参数集合
	 * @return 响应对象
	 * @throws IOException
	 */
	public HttpRespons sendPost(String urlString, Map<String, String> params)
			throws IOException {
		return this.send(urlString, "POST", params, null);
	}
 
	/**
	 * 发送POST请求
	 * 
	 * @param urlString
	 *            URL地址
	 * @param params
	 *            参数集合
	 * @param propertys
	 *            请求属性
	 * @return 响应对象
	 * @throws IOException
	 */
	public HttpRespons sendPost(String urlString, Map<String, String> params,
			Map<String, String> propertys) throws IOException {
		return this.send(urlString, "POST", params, propertys);
	}
 
	/**
	 * 发送HTTP请求
	 * 
	 * @param urlString
	 * @return 响映对象
	 * @throws IOException
	 */
	private HttpRespons send(String urlString, String method,
			Map<String, String> parameters, Map<String, String> propertys)
			throws IOException {
		HttpURLConnection urlConnection = null;
 
		if (method.equalsIgnoreCase("GET") && parameters != null) {
			StringBuffer param = new StringBuffer();
			int i = 0;
			for (String key : parameters.keySet()) {
				if (i == 0)
					param.append("?");
				else
					param.append("&");
				param.append(key).append("=").append(parameters.get(key));
				i++;
			}
			urlString += param;
		}
		URL url = new URL(urlString);
		urlConnection = (HttpURLConnection) url.openConnection();
 
		urlConnection.setRequestMethod(method);
		urlConnection.setDoOutput(true);
		urlConnection.setDoInput(true);
		urlConnection.setUseCaches(false);
 
		if (propertys != null)
			for (String key : propertys.keySet()) {
				urlConnection.addRequestProperty(key, propertys.get(key));
			}
 
		if (method.equalsIgnoreCase("POST") && parameters != null) {
			StringBuffer param = new StringBuffer();
			for (String key : parameters.keySet()) {
				param.append("&");
				param.append(key).append("=").append(parameters.get(key));
			}
			urlConnection.getOutputStream().write(param.toString().getBytes());
			urlConnection.getOutputStream().flush();
			urlConnection.getOutputStream().close();
		}
 
		return this.makeContent(urlString, urlConnection);
	}
 
	/**
	 * 得到响应对象
	 * 
	 * @param urlConnection
	 * @return 响应对象
	 * @throws IOException
	 */
	private HttpRespons makeContent(String urlString,
			HttpURLConnection urlConnection) throws IOException {
		HttpRespons httpResponser = new HttpRespons();
		try {
			InputStream in = urlConnection.getInputStream();
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(in));
			httpResponser.contentCollection = new Vector<String>();
			StringBuffer temp = new StringBuffer();
			String line = bufferedReader.readLine();
			while (line != null) {
				httpResponser.contentCollection.add(line);
				temp.append(line).append("\r\n");
				line = bufferedReader.readLine();
			}
			bufferedReader.close();
 
			String ecod = urlConnection.getContentEncoding();
			if (ecod == null)
				ecod = this.defaultContentEncoding;
 
			httpResponser.urlString = urlString;
 
			httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
			httpResponser.file = urlConnection.getURL().getFile();
			httpResponser.host = urlConnection.getURL().getHost();
			httpResponser.path = urlConnection.getURL().getPath();
			httpResponser.port = urlConnection.getURL().getPort();
			httpResponser.protocol = urlConnection.getURL().getProtocol();
			httpResponser.query = urlConnection.getURL().getQuery();
			httpResponser.ref = urlConnection.getURL().getRef();
			httpResponser.userInfo = urlConnection.getURL().getUserInfo();
 
			httpResponser.content = new String(temp.toString().getBytes(), ecod);
			httpResponser.contentEncoding = ecod;
			httpResponser.code = urlConnection.getResponseCode();
			httpResponser.message = urlConnection.getResponseMessage();
			httpResponser.contentType = urlConnection.getContentType();
			httpResponser.method = urlConnection.getRequestMethod();
			httpResponser.connectTimeout = urlConnection.getConnectTimeout();
			httpResponser.readTimeout = urlConnection.getReadTimeout();
 
			return httpResponser;
		} catch (IOException e) {
			throw e;
		} finally {
			if (urlConnection != null)
				urlConnection.disconnect();
		}
	}
 
	/**
	 * 默认的响应字符集
	 */
	public String getDefaultContentEncoding() {
		return this.defaultContentEncoding;
	}
 
	/**
	 * 设置默认的响应字符集
	 */
	public void setDefaultContentEncoding(String defaultContentEncoding) {
		this.defaultContentEncoding = defaultContentEncoding;
	}
}
 




其次我们来看看响应对象(HttpRespons )。 响应对象其实只是一个数据BEAN ,由此来封装请求响应的结果数据,如下: Java代码
import java.util.Vector;   
    
/**  
 * 响应对象  
 */  
public class HttpRespons {   
    
    String urlString;   
    
    int defaultPort;   
    
    String file;   
    
    String host;   
    
    String path;   
    
    int port;   
    
    String protocol;   
    
    String query;   
    
    String ref;   
    
    String userInfo;   
    
    String contentEncoding;   
    
    String content;   
    
    String contentType;   
    
    int code;   
    
    String message;   
    
    String method;   
    
    int connectTimeout;   
    
    int readTimeout;   
    
    Vector<String> contentCollection;   
    
    public String getContent() {   
        return content;   
    }   
    
    public String getContentType() {   
        return contentType;   
    }   
    
    public int getCode() {   
        return code;   
    }   
    
    public String getMessage() {   
        return message;   
    }   
    
    public Vector<String> getContentCollection() {   
        return contentCollection;   
    }   
    
    public String getContentEncoding() {   
        return contentEncoding;   
    }   
    
    public String getMethod() {   
        return method;   
    }   
    
    public int getConnectTimeout() {   
        return connectTimeout;   
    }   
    
    public int getReadTimeout() {   
        return readTimeout;   
    }   
    
    public String getUrlString() {   
        return urlString;   
    }   
    
    public int getDefaultPort() {   
        return defaultPort;   
    }   
    
    public String getFile() {   
        return file;   
    }   
    
    public String getHost() {   
        return host;   
    }   
    
    public String getPath() {   
        return path;   
    }   
    
    public int getPort() {   
        return port;   
    }   
    
    public String getProtocol() {   
        return protocol;   
    }   
    
    public String getQuery() {   
        return query;   
    }   
    
    public String getRef() {   
        return ref;   
    }   
    
    public String getUserInfo() {   
        return userInfo;   
    }   
    
}  

import java.util.Vector;
 
/**
 * 响应对象
 */
public class HttpRespons {
 
	String urlString;
 
	int defaultPort;
 
	String file;
 
	String host;
 
	String path;
 
	int port;
 
	String protocol;
 
	String query;
 
	String ref;
 
	String userInfo;
 
	String contentEncoding;
 
	String content;
 
	String contentType;
 
	int code;
 
	String message;
 
	String method;
 
	int connectTimeout;
 
	int readTimeout;
 
	Vector<String> contentCollection;
 
	public String getContent() {
		return content;
	}
 
	public String getContentType() {
		return contentType;
	}
 
	public int getCode() {
		return code;
	}
 
	public String getMessage() {
		return message;
	}
 
	public Vector<String> getContentCollection() {
		return contentCollection;
	}
 
	public String getContentEncoding() {
		return contentEncoding;
	}
 
	public String getMethod() {
		return method;
	}
 
	public int getConnectTimeout() {
		return connectTimeout;
	}
 
	public int getReadTimeout() {
		return readTimeout;
	}
 
	public String getUrlString() {
		return urlString;
	}
 
	public int getDefaultPort() {
		return defaultPort;
	}
 
	public String getFile() {
		return file;
	}
 
	public String getHost() {
		return host;
	}
 
	public String getPath() {
		return path;
	}
 
	public int getPort() {
		return port;
	}
 
	public String getProtocol() {
		return protocol;
	}
 
	public String getQuery() {
		return query;
	}
 
	public String getRef() {
		return ref;
	}
 
	public String getUserInfo() {
		return userInfo;
	}
 
}




最后,让我们写一个应用类,测试以上代码是否正确

Java代码
import com.yao.http.HttpRequester;   
import com.yao.http.HttpRespons;   
    
public class Test {   
    public static void main(String[] args) {   
        try {   
            HttpRequester request = new HttpRequester();   
            HttpRespons hr = request.sendGet("http://www.csdn.net");   
    
            System.out.println(hr.getUrlString());   
            System.out.println(hr.getProtocol());   
            System.out.println(hr.getHost());   
            System.out.println(hr.getPort());   
            System.out.println(hr.getContentEncoding());   
            System.out.println(hr.getMethod());   
               
            System.out.println(hr.getContent());   
    
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
} 
分享到:
评论
1 楼 xiehongdong 2012-09-05  
lz啊,你的这篇文章被人传到百度文库了,不知道是不是你自己上传的,如果不是,我来举报下http://wenku.baidu.com/view/229ddc3043323968011c9269.html

相关推荐

    JAVA发送HTTP请求,返回HTTP响应内容

    【JAVA发送HTTP请求,返回HTTP响应内容】 在Java编程中,发送HTTP请求并接收响应是常见的网络通信操作,尤其在Web服务的开发和测试中。本文将详细介绍如何使用Java发送HTTP请求并处理响应内容。 首先,我们需要...

    Java发送Http请求,解析html返回

    Java发送Http请求,解析html返回

    Java编程:发送HTTP请求,返回响应内容

    总的来说,Java发送HTTP请求和处理响应涉及网络编程、HTTP协议理解、异常处理、输入/输出流操作,以及可能的HTML解析和网页爬虫技术。这些知识对于任何想要构建Web客户端应用或进行数据抓取的开发者来说都是必不可少...

    java发送http请求

    下面我们将详细讨论如何使用Java发送HTTP请求,以及如何处理返回的HTTP响应内容。 首先,创建一个名为`HttpRequester`的类,用于封装HTTP请求的逻辑。在类中,定义一个默认的字符编码`defaultContentEncoding`,...

    JAVA实现HTTP请求

    这个是我自己集成框架的时候写的一个HTTP请求的辅助类,主要是通过HttpURLConnection 来实现JAVA的HTTP请求,有的人会问、为什么有些网站发请求没问题,有些网站发请求却返回数据,在给网站发送请求的时候,请看清楚...

    JAVA发送HTTP请求,返回HTTP响应内容,应用及实例代码

    `send()`方法是核心,它根据请求类型设置HTTP连接,处理POST请求的请求体,读取响应内容并封装成`HttpResponse`对象返回。 `HttpResponse`类可以设计为: ```java public class HttpResponse { private int ...

    Java发送Http请求工具类

    这是一个java发送get、post请求,并得到返回结果的工具类。

    java发送http/https请求(get/post)Demo,亲测可用

    这里我们将深入探讨如何使用Java发送GET和POST请求,以及处理JSON数据。 首先,让我们关注GET请求。GET请求主要用于从服务器获取资源,其参数通常包含在URL中。在Java中,可以使用`HttpURLConnection`类或者第三方...

    java发送http请求工具类

    4. **发送请求体**:对于POST请求,需要写入请求体,可以通过`getOutputStream()`获取输出流并写入数据。 ```java try(OutputStream os = connection.getOutputStream()) { os.write(jsonData.getBytes...

    java发送http请求报文json

    ### Java 发送 HTTP ...通过设置合适的连接属性、构建 JSON 数据、发送请求并读取响应数据,你可以完成与远程服务器的数据交互。这种能力对于现代软件开发非常重要,尤其是在涉及到前后端分离架构的应用程序开发中。

    java发送http请求并获取状态码的简单实例

    在Java编程中,发送HTTP请求并获取状态码是常见的网络通信任务。HTTP状态码是服务器对客户端请求的响应,它提供了关于请求是否成功、需要进一步操作还是存在错误等信息。以下是一个简单的Java实例,展示了如何实现这...

    java HttpClient 发送GET请求和带有表单参数的POST请求教程例子

    - 在发送请求之前,确保网络连接正常。 - 使用`try-catch-finally`结构来捕获可能的异常,并确保在`finally`块中释放资源,避免内存泄漏。 - 在处理响应时,注意编码问题,例如上述代码中的“UTF-8”。 - 如果在生产...

    JAVA发送POST请求,如何使用JAVA发送POST请求

    发送请求:通过HttpURLConnection类中的getOutputStream()方法获取输出流并写入请求体,从而发送POST请求。 处理响应:通过HttpURLConnection类中的getInputStream()方法获取输入流并读取响应体,从而处理服务器...

    Java发送HTTP请求GET/POST测试

    在发送请求后,通常需要读取服务器返回的响应。HttpURLConnection类提供了响应码(通过getResponseCode()获得)和响应头(通过getHeaderFields()获得)等信息,以及通过getInputStream()或getErrorStream()获取响应...

    java后台请求http并保持Session

    在Java编程中,后台请求HTTP并保持Session是一个常见的任务,特别是在需要访问受保护的Web资源时,例如登录后的网页数据。下面将详细讲解这个过程,包括GET和POST方法的使用,以及Session管理。 首先,我们需要了解...

    Android向Java后台发送请求并返回Json数据

    本教程将详细讲解如何从Android客户端向Java后台发送请求,并接收返回的Json数据。 一、HTTP请求库的选择 在Android中,我们可以使用多种库来实现网络请求,如HttpURLConnection(原生API)、Volley、Retrofit、...

    java中main方法发送httpPost请求

    发送请求并读取响应状态码: ```java connection.connect(); int responseCode = connection.getResponseCode(); ``` 6. **处理响应** 读取服务器返回的数据,可能是JSON、XML或其他格式: ```java try...

    java-http请求jar包

    Java发送HTTP请求是进行网络通信的基本操作之一,广泛应用于数据获取、API调用等场景。在Java中,Apache HttpClient库是一个强大的工具,它允许开发者高效、灵活地处理HTTP请求。这个"java-http请求jar包"实际上就是...

    java http 发送xml报文(java发送xml报文实例+参数)

    本篇文章将深入探讨如何在Java中利用HTTP协议发送XML报文,并通过实例和参数解析具体实现步骤。 首先,我们需要引入Java的HttpURLConnection类,这是Java标准库提供的HTTP客户端接口。发送XML报文通常涉及到POST或...

    java 通过发送json,post请求,返回json数据的方法

    java 通过发送json,post请求,返回json数据的方法 java 通过发送json,post请求,返回json数据的方法

Global site tag (gtag.js) - Google Analytics