转载自http://www.iteye.com/topic/154258
首先让我们先构建一个请求类(HttpRequester)。
该类封装了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;
}
}
其次我们来看看响应对象(HttpRespons)。响应对象其实只是一个数据BEAN,由此来封装请求响应的结果数据,如下:
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 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();
}
}
}
分享到:
相关推荐
总的来说,Java发送HTTP请求和处理响应涉及网络编程、HTTP协议理解、异常处理、输入/输出流操作,以及可能的HTML解析和网页爬虫技术。这些知识对于任何想要构建Web客户端应用或进行数据抓取的开发者来说都是必不可少...
6. 发送请求并获取响应码、响应消息和响应内容。 7. 关闭连接。 通过以上步骤,开发者可以实现自定义的HTTP客户端,实现与远程服务的交互。在实际项目中,理解这些基本概念和步骤对于构建高效、可靠的网络应用程序...
下面我们将详细讨论如何使用Java发送HTTP请求,以及如何处理返回的HTTP响应内容。 首先,创建一个名为`HttpRequester`的类,用于封装HTTP请求的逻辑。在类中,定义一个默认的字符编码`defaultContentEncoding`,...
### Java 发送 HTTP ...通过设置合适的连接属性、构建 JSON 数据、发送请求并读取响应数据,你可以完成与远程服务器的数据交互。这种能力对于现代软件开发非常重要,尤其是在涉及到前后端分离架构的应用程序开发中。
发送请求:通过HttpURLConnection类中的getOutputStream()方法获取输出流并写入请求体,从而发送POST请求。 处理响应:通过HttpURLConnection类中的getInputStream()方法获取输入流并读取响应体,从而处理服务器...
然而,为了提高代码的可复用性和易用性,这个工具类通常会封装成一个静态方法,接收请求URL、方法、参数等作为参数,返回响应结果。此外,还可以添加异常处理,处理网络错误、超时等问题。 请注意,虽然`...
在给定的代码片段中,主要展示了如何使用Java中的Apache HttpClient库发送一个包含XML数据的POST请求,并接收响应。下面是对关键部分的详细分析: 1. **导入必要的库**:代码首先导入了处理网络请求、输入输出流...
在发送请求后,通常需要读取服务器返回的响应。HttpURLConnection类提供了响应码(通过getResponseCode()获得)和响应头(通过getHeaderFields()获得)等信息,以及通过getInputStream()或getErrorStream()获取响应...
发送请求并读取响应状态码: ```java connection.connect(); int responseCode = connection.getResponseCode(); ``` 6. **处理响应** 读取服务器返回的数据,可能是JSON、XML或其他格式: ```java try...
- 在发送请求之前,确保网络连接正常。 - 使用`try-catch-finally`结构来捕获可能的异常,并确保在`finally`块中释放资源,避免内存泄漏。 - 在处理响应时,注意编码问题,例如上述代码中的“UTF-8”。 - 如果在生产...
Java发送HTTP请求是进行网络通信的基本操作之一,广泛应用于数据获取、API调用等场景。在Java中,Apache HttpClient库是一个强大的工具,它允许开发者高效、灵活地处理HTTP请求。这个"java-http请求jar包"实际上就是...
发送完XML后,读取服务器返回的响应码和响应体: ```java int responseCode = connection.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader in = new ...
Java中的HTTP异步请求是一种高效的网络通信方式,它允许程序在发送HTTP请求后不等待响应,而是立即继续执行其他任务,当服务器响应时,通过回调函数处理结果。这种方式避免了同步请求时线程阻塞的问题,提高了应用的...
Java 中的 HTTP 请求实践 在 Java 中发送 GET 和 POST 请求是...在 Java 中使用 Apache HttpClient 库可以非常方便地发送 HTTP 请求和处理响应。同时,我们也使用了 Logger 来记录日志,以便 debug 程序并记录日志。
在Java编程中,发送HTTP请求并获取状态码是常见的网络通信任务。HTTP状态码是服务器对客户端请求的响应,它提供了关于请求是否成功、需要进一步操作还是存在错误等信息。以下是一个简单的Java实例,展示了如何实现这...
### JAVA发送HttpClient请求及接收请求结果过程 #### 一、概述 在Java开发过程中,经常需要与外部系统进行HTTP通信,比如发送POST或GET请求来获取数据或提交数据。Apache HttpClient是一个强大的HTTP客户端库,提供...
Java发送XML报文的过程涉及多个层面的知识,包括HTTP协议的理解、XML的编写、Java的网络编程等。掌握这些技能对于任何希望在Web开发领域有所作为的开发者来说都是必要的。通过深入学习和实践,可以更高效地处理复杂...
总结,Android向Java后台发送请求并返回Json数据涉及的关键步骤包括选择网络请求库、设置请求参数、发送请求、处理响应以及解析Json数据。通过以上步骤,开发者可以实现Android客户端与后台服务的高效通信。在实际...
在 Java 中,需要处理发送请求时可能出现的异常,例如连接超时、网络异常等。可以使用 `try-catch` 块来捕获异常,并进行处理。 本文介绍了 Java 发送 HTTP 请求上传文件功能的实例代码,涵盖了发送 GET 请求、发送...