转载自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`,...
发送请求:通过HttpURLConnection类中的getOutputStream()方法获取输出流并写入请求体,从而发送POST请求。 处理响应:通过HttpURLConnection类中的getInputStream()方法获取输入流并读取响应体,从而处理服务器...
Java 中的 HTTP 请求实践 在 Java 中发送 GET 和 POST 请求是...在 Java 中使用 Apache HttpClient 库可以非常方便地发送 HTTP 请求和处理响应。同时,我们也使用了 Logger 来记录日志,以便 debug 程序并记录日志。
这个代码的意义在于展示了如何使用Java中的HttpClient库发送HTTP请求,并处理响应结果。在实际开发中,我们经常需要与Web服务进行交互,例如查询数据库、提交表单等。通过学习这个示例,你可以了解到如何使用...
在 Java 中,需要处理发送请求时可能出现的异常,例如连接超时、网络异常等。可以使用 `try-catch` 块来捕获异常,并进行处理。 本文介绍了 Java 发送 HTTP 请求上传文件功能的实例代码,涵盖了发送 GET 请求、发送...
java实现get请求post请求,文件传输 /** * 发送https请求 * @param requestUrl 请求地址 * @param requestMethod 请求方式(GET、POST) * @param outputStr 提交的数据 * @return 返回微信服务器响应的信息 ...
`sendGet` 方法的工作原理是将参数拼接在 URL 后面,形成一个完整的 GET 请求 URL,然后通过 `HttpURLConnection` 连接到该 URL 并发送请求。 **发送 POST 请求** POST 请求通常用于向服务器提交数据,例如表单数据...
发送请求后,可以从响应中获取信息。首先检查响应码: ```java int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 处理成功 } else { // 处理错误 } ...
(method 表示请求方式, url 请求路径, asynch 是否异步,对于 asynch 的值通常不会设置, 默认是true,表示异步发送请求) send(content) :向服务器发送请求 属性: onreadystatechange :状态回调函数 ...
4. **处理响应**:执行请求后,需要检查HTTP状态码以确认请求是否成功,同时解析返回的响应内容,这通常包含发送结果的反馈。 ```java String response = postMethod.getResponseBodyAsString(); if (statusCode ==...
4. 获取响应:发送请求后,客户端会接收到服务器的响应。响应包括状态码、响应头和可能的响应体。 在描述中提到的问题,“HTTP/1.1 302 Found”是一个HTTP状态码,表示临时重定向。当服务器接收到请求后,发现资源...
3. `httpGetRequest()` 方法:该方法用于发送 GET 请求,并返回响应结果。 使用示例 下面是一个使用 HttpUtils 工具类发送 GET 请求的示例: ```java String url = "https://www.example.com"; String result = ...
使用 HttpClient 发送 GET 请求需要创建一个 HttpGet 对象,并设置请求的 URL,然后使用 HttpClient.execute() 方法发送请求,获取响应数据。 代码实现: ```java public static String httpGet(String url, String...
上述代码中,`execute`方法会发送请求并返回一个`CloseableHttpResponse`对象,其中包含了服务器的响应状态和响应实体。`getStatusLine()`方法返回HTTP状态码,如200表示成功。`HttpEntity`对象代表了响应体,可以...
在Java编程语言中,HTTP(超文本传输协议)请求是用来与服务器进行通信的重要方式,它允许客户端(如浏览器或应用程序)向服务器发送数据并获取响应。在这个场景中,我们有两个核心类:HttpRequester.java和...
在Java中,可以使用HttpURLConnection或者Apache HttpClient库来发送HTTP POST请求。这里我们使用HttpURLConnection,因为它是Java的标准库,无需额外引入依赖。 ```java URL url = new URL(...