http编码。今天遇到获取网页上的数据,用HTTP的GET请求访问url获取资源,网上有相应的方法。以前一直不知道什么事rest风格,现在我想就是开一个Controller,然后使人可以调用你的后台代码。((value=“xxx”))
@Controller
public class getWebDataController {
public List<JSONObject> roadlist = new ArrayList<JSONObject>();
public List<JSONObject> jamlist = new ArrayList<JSONObject>();
public List<JSONObject> numlist = new ArrayList<JSONObject>();
/*public getWebDataController(){
System.out.println("初始化getWebDataController");
}*/
@Autowired
private InsertAllDataService service;
@ResponseBody
@RequestMapping(value="/getWebData.htm", produces = "text/html;charset=utf-8")
public String getWebData(HttpServletRequest request, HttpServletResponse response)
throws ParserConfigurationException, SAXException, IOException, DocumentException{
this.setAccessHeader(response);
roadlist.clear();
jamlist.clear();
numlist.clear();
/*String url1 = com.enjoyor.soa.traffic.server.ubms.util.SpringReader.getProperty("url1")*/
String url1 = "http://www.hzjtydzs.com/web/xmlsvc/currentRoadSpeed.aspx?rank=%E7%BB%86%E7%B2%92%E5%BA%A6&order=asc&areaid=%E6%A0%B8%E5%BF%83%E5%8C%BA";
String url2 = "http://www.hzjtydzs.com/web/xmlsvc/currentNumberData.aspx";
String url3 = "http://www.hzjtydzs.com/web/xmlsvc/currentJamIndex.aspx";
String returnString = "";
String[] urls = new String[] { url1, url2, url3 };
getNode getnode = new getNode();
for (int i = 0; i < urls.length; i++) {
String url = urls[i];
String param = "";
String fileLac = HttpRequest.sendGet(url, param);
//出错位置,开始由于是在tomcat服务器下,没有办法调试,只能通过日志和打印收集信息,发现是DocumentHelper.parseText(fileLac);这句报错,于是开始在这里修改,但是很快发现,Helper文件是别人发布好的,无法修改,那么只能在此之前处理。这里是我没有想到的,思维在此出现阻碍,我没有进去HttpRequest去看,我以为这个也是发布好的类,没想到在此修改。是的,错误出现在parseText那里,但是真正的根源,问题的本质却是在前面一句代码里。
Document doc = DocumentHelper.parseText(fileLac);
Element rootElt = doc.getRootElement(); // 获取根节点
// getNode.getNodes(rootElt,"");
if (url.indexOf("NumberData") > 0) {
numlist = (List<JSONObject>)getnode.getNodes(rootElt, "").get("numlist");// 从根节点开始遍历所有节点
}
if (url.indexOf("RoadSpeed") > 0) {
roadlist = (List<JSONObject>)getnode.getNodes(rootElt, "").get("roadlist");
}
if (url.indexOf("JamIndex") > 0) {
jamlist = (List<JSONObject>)getnode.getNodes(rootElt, "").get("jamlist");
}
}
if(numlist.size()>0){
returnString += numlist.toString();
}
if(roadlist.size()>0){
returnString += roadlist.toString();
}
if(jamlist.size()>0){
returnString += jamlist.toString();
}
return returnString;
}
/**
* 跨域声明
* @param response
*/
private void setAccessHeader(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
}
}
备份
package com.enjoyor.soa.traffic.server.sjjx.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpRequest {
/**
* 向指定URL发送GET方法的请求
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
String strUrl = "";
try {
HttpClient httpClient=new HttpClient();
GetMethod getMethod=null;
if(param == ""){
strUrl = url ;
}else{
strUrl = url + "?" + param;
}
getMethod=new GetMethod(strUrl);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
httpClient.executeMethod(getMethod);
// byte[] bResposeBody = getMethod.getResponseBody();
//String strResposeBody = new String(bResposeBody);
String strResposeBody = new String(getMethod.getResponseBody().getBytes("iso8859-1"),"utf-8"); //修改编码
result = strResposeBody;
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
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;
}
/* public static void main(String args[]) throws ParserConfigurationException, SAXException, IOException{
String url="http://www.hzjtydzs.com/web/xmlsvc/currentJamIndex.aspx?_=1482462966169";
String param = "";
String fileLac = sendGet(url, param);
Element aaa = XmlHelper.getRootElement(fileLac);
}*/
}