最近在写有关java后台url请求,才明白这是java的网络编程内容,在次记录一下一套java网络编程请求url代码,基本是通用的,只要修改一下url地址、请求参数、请求方式即可。
public static String getWeixinInterface (String url) throws IOException {
StringBuffer bufferRes = new StringBuffer();
try {
URL realUrl = new URL(url);
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 连接超时
conn.setConnectTimeout(25000);
// 读取超时 --服务器响应比较慢,增大时间
conn.setReadTimeout(25000);
HttpURLConnection.setFollowRedirects(true);
// 请求方式
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0");
//已知请求url关键字
conn.setRequestProperty("Referer", "https://api.weixin.qq.com/");
OutputStream os = conn.getOutputStream();
String param = new String();
param = "发送请求参数";
os.write(param.getBytes());
conn.connect();
// 获取URLConnection对象对应的输出流
InputStream in = conn.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in,"UTF-8"));
String valueString = null;
while ((valueString=read.readLine())!=null){
bufferRes.append(valueString);
}
System.out.println(bufferRes.toString());
in.close();
if (conn != null) {
// 关闭连接
conn.disconnect();
}
return bufferRes.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
上面请求返回的数据是如果是XML格式,可用以下这段代码把XML格式------>map集合
public static Map doXMLParse(String strxml) throws JDOMException, IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
if(null == strxml || "".equals(strxml)) {
return null;
}
Map m = new HashMap();
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while(it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List children = e.getChildren();
if(children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = XMLUtil.getChildrenText(children);
}
m.put(k, v);
}
//关闭数据流
in.close();
return m;
}