[TOC]
Http通讯Util,可以通过请求参数为jsonstring来通讯,也可以把请求参数放在request中进行通讯
HttpUtil类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtil {
/**
* 向指定URL发送GET方法的请求,参数都放在HttpRequestServlet request的内容中
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和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();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("【HTTP发送GET请求出现异常】:访问URL:"+url+",错误:"+e.getMessage());
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
System.out.println("【HTTP请求关闭输入流异常】:访问URL:"+url+",错误:"+e2.getMessage());
}
}
return result;
}
/**
* 通过一个jsonString参数来传递数据,POST请求
* 请求地址的接口的参数必须为String data
* @param json
* @param urls
* @return
*/
public static String jsonPost(String urls,String json) {
OutputStream out = null;
BufferedReader inputStreamReader = null;
StringBuffer buffer=null;
try {
URL url = new URL(urls);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST"); // 设置请求方式
connection.setRequestProperty("Accept-Charset", "utf-8"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置发送数据的格式
connection.connect();
out = connection.getOutputStream();
String pushData = "data="+json;
out.write(pushData.getBytes("UTF-8"));
out.flush();
out.close();
//获取响应
inputStreamReader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
// 读取响应
buffer = new StringBuffer();
String data= new String("");
while ((data = inputStreamReader.readLine()) != null) {
buffer.append(data);
}
while ((data = inputStreamReader.readLine()) != null) {
buffer.append(data);
}
}catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(inputStreamReader != null){
inputStreamReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return buffer.toString();
}
}