/**
* get方式请求接口链接
* @param strUrl 链接地址
* @param params 参数
* @return
*/
public static String doGet(String strUrl ,Map<String, Object> params) {
String result = "";
try {
//判断参数params是否为空
if (null != params && params.size() > 0 ) {
strUrl += "?";
for (Entry<String, Object> m : params.entrySet()) {
String key = m.getKey().toString();
String value = m.getValue().toString();
strUrl += key+"="+URLEncoder.encode(value, "UTF-8")+"&";
}
strUrl = strUrl.substring(0, strUrl.lastIndexOf("&"));
}
URL url = new URL(strUrl);
// 使用HttpURLConnection打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 连接url引用资源的链接
conn.connect();
// 以流的形式获取到链接的内容
InputStream stream = conn.getInputStream();
int len = 0;
byte[] buffer = new byte[1024];// 缓存
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while ((len = stream.read(buffer)) != -1) {// 直到读到文件结束
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();// 得到文件的二进制数据
outStream.close();
stream.close();
result = new String(data,"UTF-8");
conn.disconnect();
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
*
* @Description: post方式请求接口链接
* @param @param strUrl
* @param @param params
* @param @return
* @return String
* @throws
* @author demo
* @date 2014年10月31日
*/
public static String doPost(String strUrl, Map<String, Object> params) {
String result = "";
try {
URL url = new URL(strUrl);
// 使用HttpURLConnection打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// 设置 URL 请求的方法
conn.setDoInput(true);// 允许接收输入
conn.setDoOutput(true);// 允许接收输出
// conn.setRequestProperty("Content-Type",
// "application/x-www-form-urlencoded");
conn.connect();// 打开到此 URL 引用的资源的通信链接
// 用DataOutputStream.writeBytes(content)将请求参数写入进去
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
String str = "";
//判断参数params是否为空
if (null != params && params.size() > 0) {
for (Entry<String, Object> m : params.entrySet()) {
String key = m.getKey().toString();
String value = m.getValue().toString();
str += key+"="+URLEncoder.encode(value, "UTF-8")+"&";
}
System.out.println(str.substring(0, str.lastIndexOf("&")));
dos.writeBytes(str.substring(0, str.lastIndexOf("&")));
dos.close();
}
// 获取该连接的输入
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1024];// 缓存
int len = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while ((len = stream.read(buffer)) != -1) {// 直到读到文件结束
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();// 得到文件的二进制数据
outStream.close();
stream.close();
result = new String(data,"UTF-8");
conn.disconnect();// 指示服务器近期不太可能有其他请求
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}