Java常用的网络请求函数详解
网络请求是Java中的一个重要部分,它可以使我们的应用程序进行与网路交互,比如发送和接收数据等。Java中有很多网络请求函数,本文将介绍Java常用的网络请求函数,包括URLConnection和HttpClient。
一、URLConnection
URLConnection是Java中一个基本的网络请求工具,它不仅支持HTTP协议,还支持FTP和Gopher等协议。使用URLConnection可以发送GET和POST请求,并且可以设置请求头和请求体。
1.发送GET请求
使用URLConnection发送GET请求需要实例化URL对象,然后使用openConnection()方法获取URLConnection对象,最后通过输入流来获取服务器返回的数据。
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用 finally 关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
2.发送POST请求
与发送GET请求类似,使用URLConnection发送POST请求需要实例化URL对象,然后使用openConnection()方法获取URLConnection对象,并设置请求方法为POST,然后通过输出流向服务器发送数据,最后通过输入流来获取服务器返回的数据。
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
二、HttpClient
HttpClient是Apache软件基金会开发的一款开源的HTTP客户端程序库。它可以用于发送HTTP请求和接收HTTP响应,在Android开发中也非常常用。HttpClient相比URLConnection更加强大和灵活,同时也更容易使用。
1.发送GET请求
使用HttpClient发送GET请求需要实例化HttpClient对象,然后实例化HttpGet对象并设置请求头和请求参数,最后通过执行HttpGet方法并使用HttpResponse对象来获取服务器返回的数据。
public static String sendGet(String url) {
HttpClient httpClient = new DefaultHttpClient();
String result = "";
try {
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
result = convertStreamToString(instreams);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
public static String convertStreamToString(InputStream is) {
String result = "";
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
result = baos.toString();
baos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
2.发送POST请求
与发送GET请求类似,使用HttpClient发送POST请求需要实例化HttpClient对象,然后实例化HttpPost对象并设置请求头和请求体,最后通过执行HttpPost方法并使用HttpResponse对象来获取服务器返回的数据。
public static String sendPost(String url, String param) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String result = "";
try {
StringEntity entity = new StringEntity(param, HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
InputStream instreams = httpEntity.getContent();
result = convertStreamToString(instreams);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
三、总结
使用Java发送网络请求,我们可以使用URLConnection和HttpClient两种工具,根据实际项目需要选择合适的方法,通常来说,HttpClient更加灵活和强大,可以实现更多的功能,在Android开发中使用也更加方便。
