C#如何在Http Request Header中加入参数

请问如何在Http Request Header中加入参数
使用C#调用讯飞的AIUI文本语义,一直返回授权请求头参数为空

2个回答

context.Request.Headers.Add("key", "")
或者
Request.Headers.Add("key", "")

guzicheng1990
guzicheng1990 我这样加了没有用 一直返回10004
大约 2 年之前 回复
zml_moxueli
呓语的风 回复qq_38219740: 对 有些接口需要把签名放header里
大约 2 年之前 回复
qq_38219740
qq_38219740 在调用本接口时,需要在Http Request Header中加入参数X-Param; 这是要求,我的理解对吗?
大约 2 年之前 回复

哥们你的调试通过了吗?我用c#调用怎么老返回10004

guzicheng1990
guzicheng1990 回复qq_38219740: 你好 我C#调用也一直返回10004不知道哪里的问题 能帮我一下么 我联系qq408141471 万分感激
大约 2 年之前 回复
guzicheng1990
guzicheng1990 请问你解决了么? 我也是一模一样的返回10004
大约 2 年之前 回复
qq_38219740
qq_38219740 好用了 615171491
大约 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
PHP Curl 转C# libcurl 或C#代码, PHP POST 提交XML转C#×
PHP代码 ``` $account = 'abc'; $password = 'abc123'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.fdd.com/new_orders.php/"); curl_setopt($ch, CURLOPT_USERPWD, "$account.':'.$password"); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);//CURLAUTH_ANY curl_setopt($ch, CURLOPT_PROXY,'127.0.0.1:8888');//设置代理服务器 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 4); curl_setopt($ch, CURLOPT_POSTFIELDS, array('xml_request' => "$xml_request")); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close')); $result = curl_exec($ch);// 执行并获取HTML文档内容 curl_close($ch);// 释放curl句柄 header( "Content-Type: text/xml; charset=UTF-8"); echo $result; ``` 需要转成C# libCurl 或C#代码, 网上 很少C# libCrul资料,没数据返回,请指点 ``` Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL); Easy easy = new Easy(); Easy.WriteFunction wf = new Easy.WriteFunction(OnWriteData); easy.SetOpt(CURLoption.CURLOPT_URL, URL); easy.SetOpt(CURLoption.CURLOPT_USERPWD, Account + ":" + password); easy.SetOpt(CURLoption.CURLOPT_HTTPAUTH,"0" ); easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, false); easy.SetOpt(CURLoption.CURLOPT_TIMEOUT, "4"); easy.SetOpt(CURLoption.CURLOPT_POST, true); easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS, XMLData); easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, "Content-Type: text/xml; charset=UTF-8"); easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf); //easy.SetOpt(CURLoption.CURLOPT_POST, ture); easy.Perform(); easy.Cleanup(); Curl.GlobalCleanup(); ``` 直接给C#代码参考,不胜感激
c#模拟登陆 返回500错误
我想用c#模拟登陆一个网站,然后再对网站进行操作,post参数也很简单,但是为什么返回500错误呢? ![图片说明](https://img-ask.csdn.net/upload/201603/31/1459414065_362884.jpg) ![图片说明](https://img-ask.csdn.net/upload/201603/31/1459414075_702532.png) ![图片说明](https://img-ask.csdn.net/upload/201603/31/1459414082_979129.jpg) ![图片说明](https://img-ask.csdn.net/upload/201603/31/1459414093_528164.png) ![图片说明](https://img-ask.csdn.net/upload/201603/31/1459414100_67423.png) ``` using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; namespace emulateLoginBaidu { class HTMLHelper { public static CookieContainer GetCooKie(string loginUrl, string postdata, HttpHeader header) { HttpWebRequest request = null; HttpWebResponse response = null; try { CookieContainer cc = new CookieContainer(); request = (HttpWebRequest)WebRequest.Create(loginUrl); request.Method = header.method; request.ContentType = header.contentType; byte[] postdatabyte = Encoding.UTF8.GetBytes(postdata); request.ContentLength = postdatabyte.Length; request.AllowAutoRedirect = false; request.CookieContainer = cc; request.KeepAlive = true; //提交请求 Stream stream; stream = request.GetRequestStream(); stream.Write(postdatabyte, 0, postdatabyte.Length); stream.Close(); //接收响应 response = (HttpWebResponse)request.GetResponse(); response.Cookies = request.CookieContainer.GetCookies(request.RequestUri); CookieCollection cook = response.Cookies; //Cookie字符串格式 string strcrook = request.CookieContainer.GetCookieHeader(request.RequestUri); return cc; } catch (Exception ex) { throw ex; } } /// <summary> /// 获取html /// </summary> /// <param name="getUrl"></param> /// <param name="cookieContainer"></param> /// <param name="header"></param> /// <returns></returns> public static string GetHtml(string getUrl, CookieContainer cookieContainer, HttpHeader header) { Thread.Sleep(1000); HttpWebRequest httpWebRequest = null; HttpWebResponse httpWebResponse = null; try { httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl); httpWebRequest.CookieContainer = cookieContainer; httpWebRequest.ContentType = header.contentType; httpWebRequest.ServicePoint.ConnectionLimit = header.maxTry; httpWebRequest.Referer = getUrl; httpWebRequest.Accept = header.accept; httpWebRequest.UserAgent = header.userAgent; httpWebRequest.Method = "GET"; httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream responseStream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8); string html = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); httpWebRequest.Abort(); httpWebResponse.Close(); return html; } catch (Exception e) { if (httpWebRequest != null) httpWebRequest.Abort(); if (httpWebResponse != null) httpWebResponse.Close(); return string.Empty; } } } public class HttpHeader { public string contentType { get; set; } public string accept { get; set; } public string userAgent { get; set; } public string method { get; set; } public int maxTry { get; set; } } } ``` 测试代码: ``` try { HttpHeader header = new HttpHeader(); header.accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; header.contentType = "application/x-www-form-urlencoded"; header.method = "POST"; header.userAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0"; header.maxTry = 300; CookieContainer cookieContainer = new CookieContainer(); cookieContainer = HTMLHelper.GetCooKie("https://www.wish.com/api/email-login", "email=oxvbgzo66627404%40163.com&password=ai49425&_buckets=&_experiments=", header); string html = HTMLHelper.GetHtml("https://www.wish.com", cookieContainer, header); MessageBox.Show(html); } catch (Exception ee) { MessageBox.Show(ee.Message); } ```
C# 数据库 gridview问题
DataBinding:“System.Data.DataRowView”不包含名为“vcompanyname”的属性。 百度的大多数答案的意思是查询生成的ds中没有vcompanyname字段,但我的查询语句确实是有的,有还人说的session的问题,但没具体解释原因或者解决方案。 问题具体如下: 表1 公司表,从公司表的联系人,链接到联系人对应的表2 联系人信息表。vcompanyname均不是2表主键。 <asp:HyperLinkField HeaderText="联系人" DataNavigateUrlFields="vcompanyname" DataNavigateUrlFormatString="~/companycontrast/List.aspx?id={0}" Text="联系人" /> 表2的gridview是动软生成的,这部分代码在生成表1时用过,是可用的,但在表2时出问题了。 Maticsoft.BLL.companycontrast bll = new Maticsoft.BLL.companycontrast(); public string strid = ""; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { gridView.BorderColor = ColorTranslator.FromHtml(Application[Session["Style"].ToString() + "xtable_bordercolorlight"].ToString()); gridView.HeaderStyle.BackColor = ColorTranslator.FromHtml(Application[Session["Style"].ToString() + "xtable_titlebgcolor"].ToString()); btnDelete.Attributes.Add("onclick", "return confirm(\"你确认要删除吗?\")"); if (Request.Params["id"] != null && Request.Params["id"].Trim() != "") { strid = Request.Params["id"]; } BindData(strid.Trim()); } } protected void btnSearch_Click(object sender, EventArgs e) { BindData(strid.Trim()); } protected void btnDelete_Click(object sender, EventArgs e) { string idlist = GetSelIDlist(); if (idlist.Trim().Length == 0) return; bll.DeleteList(idlist); BindData(strid.Trim()); } #region gridView public void BindData(string vcompanyname) { #region //if (!Context.User.Identity.IsAuthenticated) //{ // return; //} //AccountsPrincipal user = new AccountsPrincipal(Context.User.Identity.Name); //if (user.HasPermissionID(PermId_Modify)) //{ // gridView.Columns[6].Visible = true; //} //if (user.HasPermissionID(PermId_Delete)) //{ // gridView.Columns[7].Visible = true; //} #endregion DataSet ds = new DataSet(); /* StringBuilder strWhere = new StringBuilder(); if (txtKeyword.Text.Trim() != "") { #warning 代码生成警告:请修改 keywordField 为需要匹配查询的真实字段名称 strWhere.AppendFormat("keywordField like '%{0}%'", txtKeyword.Text.Trim()); } */ string strWhere = "vcompanyname = '" + vcompanyname + "'"; ds = bll.GetList(strWhere.ToString()); gridView.DataSource = ds; gridView.DataBind(); } protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e) { gridView.PageIndex = e.NewPageIndex; BindData(strid.Trim()); } protected void gridView_OnRowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { //e.Row.Cells[0].Text = "<input id='Checkbox2' type='checkbox' onclick='CheckAll()'/><label></label>"; } } protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e) { e.Row.Attributes.Add("style", "background:#FFF"); if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton linkbtnDel = (LinkButton)e.Row.FindControl("LinkButton1"); linkbtnDel.Attributes.Add("onclick", "return confirm(\"你确认要删除吗\")"); //object obj1 = DataBinder.Eval(e.Row.DataItem, "Levels"); //if ((obj1 != null) && ((obj1.ToString() != ""))) //{ // e.Row.Cells[1].Text = obj1.ToString(); //} } } protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { //#warning 代码生成警告:请检查确认真实主键的名称和类型是否正确 //int ID = (int)gridView.DataKeys[e.RowIndex].Value; //bll.Delete(ID); //gridView.OnBind(); } private string GetSelIDlist() { string idlist = ""; bool BxsChkd = false; for (int i = 0; i < gridView.Rows.Count; i++) { CheckBox ChkBxItem = (CheckBox)gridView.Rows[i].FindControl("DeleteThis"); if (ChkBxItem != null && ChkBxItem.Checked) { BxsChkd = true; //#warning 代码生成警告:请检查确认Cells的列索引是否正确 if (gridView.DataKeys[i].Value != null) { idlist += gridView.DataKeys[i].Value.ToString() + ","; } } } if (BxsChkd) { idlist = idlist.Substring(0, idlist.LastIndexOf(",")); } return idlist; } #endregion } 代码运行到 gridView.DataBind();时报错。 单步跟踪到这里时: connection.Open(); SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); command.Fill(ds, "ds"); 无法查看返回数据集ds中数据,但所涉及所有字段数据库中均存在,测试查询内容在数据库中也存在。
python3.65 urllib.request.Request()增加header报错
# coding:utf-8 import urllib.request import urllib.parse url = 'http://192.168.**.**:9080/api/transactions' header = { 'Content-Type': 'application/json' } values ={ "currentToken": { "simplifiedName": "ETH", "address": "0x5bcd4d0508bc86c48760d0805962261d260d7a88" }, "txid": "" } data = urllib.parse.urlencode(values) data = data.encode(encoding='UTF-8') request = urllib.request.Request(url, data, header) #request = urllib.request.Request(url, data) print("111") html = urllib.request.urlopen(request) print("222") html =html.read().decode('utf-8') print(html) #返回结果 报错 D:\tool\Python36\python.exe D:/Users/Administrator/PycharmProjects/coinPlatform/test/test6.py 111 Traceback (most recent call last): File "D:/Users/Administrator/PycharmProjects/coinPlatform/test/test6.py", line 21, in <module> html = urllib.request.urlopen(request) File "D:\tool\Python36\lib\urllib\request.py", line 223, in urlopen return opener.open(url, data, timeout) File "D:\tool\Python36\lib\urllib\request.py", line 532, in open response = meth(req, response) File "D:\tool\Python36\lib\urllib\request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "D:\tool\Python36\lib\urllib\request.py", line 570, in error return self._call_chain(*args) File "D:\tool\Python36\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "D:\tool\Python36\lib\urllib\request.py", line 650, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found Process finished with exit code 1 # coding:utf-8 import urllib.request import urllib.parse url = 'http://192.168.**.**:9080/api/transactions' header = { 'Content-Type': 'application/json' } values ={ "currentToken": { "simplifiedName": "ETH", "address": "0x5bcd4d0508bc86c48760d0805962261d260d7a88" }, "txid": "" } data = urllib.parse.urlencode(values) data = data.encode(encoding='UTF-8') #request = urllib.request.Request(url, data, header) request = urllib.request.Request(url, data) print("111") html = urllib.request.urlopen(request) print("222") html =html.read().decode('utf-8') print(html) 返回结果 成功 但没得到想要的结果 D:\tool\Python36\python.exe D:/Users/Administrator/PycharmProjects/coinPlatform/test/test6.py 111 222 {"code":0,"message":"success","data":{"currentToken":{},"transactions":[]}} Process finished with exit code 0
关于c#使用WebClient调用openapi接口
使用c#调用openapi接口。如下图 ![图片说明](https://img-ask.csdn.net/upload/201703/06/1488785737_987974.jpg) java代码为: ``` public static PageResponse<UIMUser> userfind() { List<CommonCondition> conditions = new ArrayList<CommonCondition>(); CommonCondition c = new CommonCondition(); c.setName("userName"); c.setDataType(DataType.String); c.setCriteriaType(CriteriaType.StartWith); c.setValue("User1"); conditions.add(c); PostMethod method = new PostMethod(endPoint + "/admin/macula-uim/user/find"); try { method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // 标识是OpenAPI请求 method.addRequestHeader(OpenApiUtils.AJAX_REQUEST_HEADER, OpenApiUtils.API_REQUEST_VALUE); // 添加POST BODY method.addParameter("page", "0"); method.addParameter("rows", "20"); method.addParameters(OpenApiUtils.getPostParams("conditions", conditions)); // 设置请求参数 method.setQueryString(OpenApiUtils.getOpenApiParams(appKey, appSecret, null, null, null, null, "zh_CN", method.getParameters())); int status = client.executeMethod(method); String content = method.getResponseBodyAsString(); if (status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { // 反序列化结果 ObjectMapperImpl mapper = new ObjectMapperImpl(); return mapper.readValue(content, new TypeReference<PageResponse<UIMUser>>() { }); } else { throw new Exception("错误的请求"); } } catch (Exception e) { e.printStackTrace(); } finally { method.releaseConnection(); } return null; } public static NameValuePair[] getPostParams(String objectName, Object obj) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); if (obj != null) { if (obj instanceof Map) { // 处理Map Map<?, ?> map = (Map<?, ?>) obj; for (Map.Entry<?, ?> entry : map.entrySet()) { Object key = entry.getKey(); Object value = entry.getValue(); if (null != value) { pairs.addAll(Arrays.asList(getPostParams(objectName + "['" + key + "']", value))); } } } else if (obj instanceof Collection) { // 处理Collection Collection<?> col = (Collection<?>) obj; Iterator<?> it = col.iterator(); int index = 0; while (it.hasNext()) { Object value = it.next(); if (null != value) { pairs.addAll(Arrays.asList(getPostParams(objectName + "[" + index++ + "]", value))); } } } else if (!BeanUtils.isSimpleProperty(obj.getClass()) && !(obj instanceof Enum) && !Date.class.isAssignableFrom(obj.getClass())) { // 处理Bean BeanWrapperImpl bean = new BeanWrapperImpl(obj); PropertyDescriptor[] ps = bean.getPropertyDescriptors(); for (PropertyDescriptor p : ps) { if (!p.getName().equals("class")) { Object value = bean.getPropertyValue(p.getName()); if (null != value) { pairs.addAll(Arrays.asList(getPostParams(objectName + "." + p.getName(), value))); } } } } else { String str = obj.toString(); // 处理简单属性 // 日期格式使用ISO8601 if (obj instanceof Date) { str = DateFormatUtils.formatISO8601((Date) obj); } pairs.add(new NameValuePair(objectName, str)); } } return pairs.toArray(new NameValuePair[pairs.size()]); } ``` 现在不清楚使用c#怎么传递第一个参数。 我自己写的代码: ``` using (WebClient client = new WebClient()) { //SyncOrgDAL dal = new SyncOrgDAL(); // List<CommonCondition> conditions = new List<CommonCondition>(); //CommonCondition c = new CommonCondition(); //c.setName("userType"); //c.setDataType(DataType.String); //c.setCriteriaType(CriteriaType.Equals); //c.setValue("User1"); //conditions.Add(c); NameValueCollection postParams = new NameValueCollection { { "conditions", "[\"conditions\":{\"UserName\":\"Exp\",\"userType\":\"Exp\"}]" }, { "page", page.ToString() }, { "rows", pagesize.ToString() } }; //NameValueCollection postParams = new NameValueCollection { { "fromId", "302264246" }, { "toId", "99999999999" } }; string passString = Parameters.GetOpenApiParams(account, passWord, null, null, null, null, "zh_CN", postParams); //passString += "&userType=EMP"; url += passString; client.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); client.Headers.Add("X-Requested-With", "OpenAPIRequest"); client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"); try { byte[] rDownData = client.UploadValues(url, "POST", postParams); var downString = Encoding.UTF8.GetString(rDownData) ?? ""; return downString; } catch (Exception ex) { return ex.ToString(); } finally { client.Dispose(); GC.Collect(); } ``` NameValueCollection postParams = new NameValueCollection { { "conditions", "[\"conditions\":{\"UserName\":\"Exp\",\"userType\":\"Exp\"}]" }, { "page", page.ToString() }, { "rows", pagesize.ToString() } }; 第一个参数什么格式。
c#bootstrap上传文件服务器打不开报错,读取二进制流的问题待解决
## html ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Krajee JQuery Plugins - &copy; Kartik</title> <link href="bootstrap.min.css" rel="stylesheet" /> <link href="fileinput.css" media="all" rel="stylesheet" type="text/css" /> <script src="Jquery.min.js"></script> <script src="fileinput.js" type="text/javascript"></script> <script src="bootstrap.min.js" type="text/javascript"></script> <script src="zh.js"></script> </head> <body> <form> <div> <div class="modal-header"> <h4 class="modal-title" id="modalShow">[请选择xml/docx]文件</h4> </div> <div class="modal-body"> <input type="file" name="model_file" id="model_file" multiple class="file-loading" /> </div> </div> </form> <script type="text/javascript"> $(function () { var control = $("#model_file"); var uploadrul = "/bootstrap-fileinput-master/examples/UploadFile.ashx"; var upObj = { language: 'zh', //设置语言 uploadUrl: uploadrul, //上传的地址 uploadExtraData: { "savepath": "/bootstrap-fileinput-master/examples/" },//上传至服务器的参数,非常重要 allowedFileExtensions: ['xml', 'docx', 'jpg', 'png', 'gif', 'rar', 'doc', 'txt'],//接收的文件后缀 showUpload: true, //显示批量上传按钮 showCaption: false,//是否显示标题 browseClass: "btn btn-primary", //按钮样式 dropZoneEnabled: true,//是否显示拖拽区域 maxFileSize: 4096,//单位为kb,如果为0表示不限制文件大小 minFileCount: 0, maxFileCount: 10, msgSizeTooLarge: " \"{name}\" 大小为({size} KB) 最大文件大小为 {maxSize} KB.请重新上传!",//文件的实际大小有些许偏差 enctype: 'multipart/form-data', validateInitialCount: true, previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!", allowedPreviewTypes: ['image']//能够预览的文件类型,如果不限制。文件预览时可能很慢 }; $('#modalShow').html("[请选择"+upObj.allowedFileExtensions+"]文件"); control.fileinput(upObj); //导入文件上传成功之后的事件 $("#model_file").on("fileuploaded", function (event, data, previewId, index) { }); //导入文件上传失败之后的事件 $('#model_file').on('fileuploaderror', function (event, data, msg) { var msg= data.response; }); }); </script> </body> </html> ``` ## ashx ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Text; namespace WebApplication1.bootstrap_fileinput_master.examples { /// <summary> /// UploadFile 的摘要说明 /// </summary> public class UploadFile : IHttpHandler { public void ProcessRequest(HttpContext context) { string json = "{\"msg\":\"上传成功!\"}"; try { //读取二进制流为什么 有问题 context.Response.ContentType = "text/plain"; Stream sr = context.Request.InputStream; byte[] bt = new byte[sr.Length]; HttpPostedFile file = context.Request.Files["model_file"]; string savepath = context.Request["savepath"];//获取文件保存的路径 string fileName = file.FileName; sr.Read(bt, 0, bt.Length); savepath = context.Server.MapPath(savepath) + "\\" + fileName; FileStream fs = new FileStream(savepath, FileMode.Create); fs.Write(bt, 0, bt.Length); fs.Close(); sr.Close(); } catch (Exception ex) { //失败时返回的参数必须加 error键 json = "{\"error\":\""+ex.Message+"\"}"; } context.Response.Write(json); context.Response.End(); } public bool IsReusable { get { return false; } } } } ``` ## 读取数据流的时候有问题,读取到上传文件的属性数据了,见下图2 ![读取数据流的时候用问题](https://img-ask.csdn.net/upload/201710/10/1507618593_496298.png) ##上传文件源数据 ![上传文件源数据](https://img-ask.csdn.net/upload/201710/10/1507618626_265907.png) ## 服务器上文件的内容 ![服务器上文件的内容](https://img-ask.csdn.net/upload/201710/10/1507618659_951615.png) **上传图片、word、excel文件后,打开失败。** ## 附件:[上传文件测试工程demo上传文件测试工程demo](https://pan.baidu.com/s/1kVsZXTt "上传文件测试工程demo")
Django服务端显示http 400错误,Invalid HTTP_HOST header
我用Python自带的HTTPHandler发送logging信息到服务器,代码如下 import logging ``` import logging.handlers logger = logging.getLogger('mylogger') http_handler = logging.handlers.HTTPHandler('localhost:8000', '/VideoParser/lYYDownloaderClientLog')#, method='POST' logger.addHandler(http_handler) logger.error('testing remote logging')在这里书写代码片 ``` 但是每次发送之后都会出现http 400,错误,并且还会显示Invalid HTTP_HOST header,如下 > Invalid HTTP_HOST header: 'localhost:8000,localhost'. The domain name provided i > s not valid according to RFC 1034/1035. > [03/Apr/2017 19:15:41] "GET /VideoParser/lYYDownloaderClientLog?filename=a.py&th > readName=MainThread&stack_info=None&processName=MainProcess&exc_text=None&create > d=1491218139.538086&levelname=ERROR&module=a&thread=3624&exc_info=None&relativeC > reated=112.00642585754395&levelno=40&pathname=C%3A%5CUsers%5Ci%5CDocuments%5CTen > cent+Files%5C2281570025%5CFileRecv%5Ca.py&msecs=538.0859375&msg=testing+remote+l > ogging&name=mylogger&args=%28%29&lineno=12&process=6700&funcName=%3Cmodule%3E HT > TP/1.1" 400 67823 我该如何修复问题? 相关代码 D:\BaiduYunDownload\编程\Python\django-test\LYYDownloaderServer\VideoParser\urls.py ``` from django.conf.urls import url from . import views app_name = 'VideoParser' urlpatterns = [ url(r'lYYDownloaderClientLog.+',views.lYYDownloaderClientLog, name='lYYDownloaderClientLog') ] ``` D:\BaiduYunDownload\编程\Python\django-test\LYYDownloaderServer\VideoParser\views.py ``` def lYYDownloaderClientLog(request): print('----666666666666---', request.GET)在这里书写代码片 ```
为什么用request-html爬取的内容为空?
以下是我的代码和运行结果,请问各位大佬为什么我运行内容为空?谢谢各位 ``` from requests_html import HTMLSession from requests_html import HTML import requests import time import json import random import sys import os import csv from fake_useragent import UserAgent# session = HTMLSession() url = 'https://car.autohome.com.cn/' #https://car.autohome.com.cn/config/series/3862.html USER_AGENTS = [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1", "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11", "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10" ] # 品牌列表 def get_bank(): response = session.get(url)#爬取网页 response.encoding='gbk' response.html.render() banks = response.html.find('div.cartree>ul>li>h3') for bank in banks: #print(bank.text) #print(bank.html) bk = bank.text start = bk.find("(") end = bk.find(")") print(bk[0:start]) print(bk[start+1:end]) print(banks) # 汽车品牌 def get_url(): current_dir = os.path.abspath('.')#返回绝对路径 print(current_dir) #print('1') file_name = os.path.join(current_dir, "\\bank.csv") print(file_name) response.encoding='gbk' # print('2') with open(file_name, 'wt', newline='') as csvfile1: header = ['bank','count', 'url'] writer = csv.writer(csvfile1) writer.writerow(header) #访问页面 response = session.get(url) #print(response) #response.html.render() banks = response.html.find('.cartree ul li h3 a') #banks = response.html.find('#cartree') print(banks) print('1') for bank in banks: #print(bank.text) #格式化 bk = bank.text print('2') print(bk) start = bk.find("(") end = bk.find(")") bank1 = bk[0:start] Num = bk[(start+1):end] url2 = url + bank.attrs.get("href", None) print(url2) save2csc(writer,bank1,Num,url2) #print(banks) csvfile1.close() # #写入CSV文件 def save2csc(writer,bank,num,url): header = ['bank','num' 'url'] writer.writerow(header) csvrow1 = [] csvrow1.append(bank) csvrow1.append(num) csvrow1.append(url) #writer.writerow(csvrow1) #print(csvrow1) if __name__ == '__main__': print("开始处理") get_url() get_bank() print("处理结束") ``` ![图片说明](https://img-ask.csdn.net/upload/201912/07/1575718518_178636.jpg)![图片说明](https://img-ask.csdn.net/upload/201912/07/1575718738_455103.jpg)
redis运行一段时间后,客户端链接不上
redis运行一天后,redis-cli或者使用jredis链接redis服务,提示连接超时或者链接拒绝。重启redis服务就可以重新使用了!大牛没帮忙看看什么问题? 配置文件如下: port 6379 tcp-backlog 511 timeout 60000 tcp-keepalive 0 loglevel debug logfile "D:\\redis-2.8.19\\redis.log" databases 16 save 900 1 save 300 10 save 60 10000 stop-writes-on-bgsave-error yes rdbcompression yes rdbchecksum yes dbfilename dump.rdb dir ./ slave-serve-stale-data yes slave-read-only yes repl-diskless-sync no repl-diskless-sync-delay 5 repl-disable-tcp-nodelay no slave-priority 100 requirepass foobared maxclients 10000 maxheap 2gb maxmemory 2gb maxmemory-policy volatile-lru appendonly no appendfsync everysec no-appendfsync-on-rewrite no auto-aof-rewrite-percentage 100 auto-aof-rewrite-min-size 64mb aof-load-truncated yes lua-time-limit 5000 slowlog-log-slower-than 10000 slowlog-max-len 128 ################################ LATENCY MONITOR ############################## # The Redis latency monitoring subsystem samples different operations # at runtime in order to collect data related to possible sources of # latency of a Redis instance. # # Via the LATENCY command this information is available to the user that can # print graphs and obtain reports. # # The system only logs operations that were performed in a time equal or # greater than the amount of milliseconds specified via the # latency-monitor-threshold configuration directive. When its value is set # to zero, the latency monitor is turned off. # # By default latency monitoring is disabled since it is mostly not needed # if you don't have latency issues, and collecting data has a performance # impact, that while very small, can be measured under big load. Latency # monitoring can easily be enalbed at runtime using the command # "CONFIG SET latency-monitor-threshold <milliseconds>" if needed. latency-monitor-threshold 0 ############################# Event notification ############################## # Redis can notify Pub/Sub clients about events happening in the key space. # This feature is documented at http://redis.io/topics/notifications # # For instance if keyspace events notification is enabled, and a client # performs a DEL operation on key "foo" stored in the Database 0, two # messages will be published via Pub/Sub: # # PUBLISH __keyspace@0__:foo del # PUBLISH __keyevent@0__:del foo # # It is possible to select the events that Redis will notify among a set # of classes. Every class is identified by a single character: # # K Keyspace events, published with __keyspace@<db>__ prefix. # E Keyevent events, published with __keyevent@<db>__ prefix. # g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... # $ String commands # l List commands # s Set commands # h Hash commands # z Sorted set commands # x Expired events (events generated every time a key expires) # e Evicted events (events generated when a key is evicted for maxmemory) # A Alias for g$lshzxe, so that the "AKE" string means all the events. # # The "notify-keyspace-events" takes as argument a string that is composed # of zero or multiple characters. The empty string means that notifications # are disabled. # # Example: to enable list and generic events, from the point of view of the # event name, use: # # notify-keyspace-events Elg # # Example 2: to get the stream of the expired keys subscribing to channel # name __keyevent@0__:expired use: # # notify-keyspace-events Ex # # By default all notifications are disabled because most users don't need # this feature and the feature has some overhead. Note that if you don't # specify at least one of K or E, no events will be delivered. notify-keyspace-events "" ############################### ADVANCED CONFIG ############################### # Hashes are encoded using a memory efficient data structure when they have a # small number of entries, and the biggest entry does not exceed a given # threshold. These thresholds can be configured using the following directives. hash-max-ziplist-entries 512 hash-max-ziplist-value 64 # Similarly to hashes, small lists are also encoded in a special way in order # to save a lot of space. The special representation is only used when # you are under the following limits: list-max-ziplist-entries 512 list-max-ziplist-value 64 # Sets have a special encoding in just one case: when a set is composed # of just strings that happen to be integers in radix 10 in the range # of 64 bit signed integers. # The following configuration setting sets the limit in the size of the # set in order to use this special memory saving encoding. set-max-intset-entries 512 # Similarly to hashes and lists, sorted sets are also specially encoded in # order to save a lot of space. This encoding is only used when the length and # elements of a sorted set are below the following limits: zset-max-ziplist-entries 128 zset-max-ziplist-value 64 # HyperLogLog sparse representation bytes limit. The limit includes the # 16 bytes header. When an HyperLogLog using the sparse representation crosses # this limit, it is converted into the dense representation. # # A value greater than 16000 is totally useless, since at that point the # dense representation is more memory efficient. # # The suggested value is ~ 3000 in order to have the benefits of # the space efficient encoding without slowing down too much PFADD, # which is O(N) with the sparse encoding. The value can be raised to # ~ 10000 when CPU is not a concern, but space is, and the data set is # composed of many HyperLogLogs with cardinality in the 0 - 15000 range. hll-sparse-max-bytes 3000 # Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in # order to help rehashing the main Redis hash table (the one mapping top-level # keys to values). The hash table implementation Redis uses (see dict.c) # performs a lazy rehashing: the more operation you run into a hash table # that is rehashing, the more rehashing "steps" are performed, so if the # server is idle the rehashing is never complete and some more memory is used # by the hash table. # # The default is to use this millisecond 10 times every second in order to # actively rehash the main dictionaries, freeing memory when possible. # # If unsure: # use "activerehashing no" if you have hard latency requirements and it is # not a good thing in your environment that Redis can reply from time to time # to queries with 2 milliseconds delay. # # use "activerehashing yes" if you don't have such hard requirements but # want to free memory asap when possible. activerehashing yes # The client output buffer limits can be used to force disconnection of clients # that are not reading data from the server fast enough for some reason (a # common reason is that a Pub/Sub client can't consume messages as fast as the # publisher can produce them). # # The limit can be set differently for the three different classes of clients: # # normal -> normal clients including MONITOR clients # slave -> slave clients # pubsub -> clients subscribed to at least one pubsub channel or pattern # # The syntax of every client-output-buffer-limit directive is the following: # # client-output-buffer-limit <class> <hard limit> <soft limit> <soft seconds> # # A client is immediately disconnected once the hard limit is reached, or if # the soft limit is reached and remains reached for the specified number of # seconds (continuously). # So for instance if the hard limit is 32 megabytes and the soft limit is # 16 megabytes / 10 seconds, the client will get disconnected immediately # if the size of the output buffers reach 32 megabytes, but will also get # disconnected if the client reaches 16 megabytes and continuously overcomes # the limit for 10 seconds. # # By default normal clients are not limited because they don't receive data # without asking (in a push way), but just after a request, so only # asynchronous clients may create a scenario where data is requested faster # than it can read. # # Instead there is a default limit for pubsub and slave clients, since # subscribers and slaves receive data in a push fashion. # # Both the hard or the soft limit can be disabled by setting them to zero. client-output-buffer-limit normal 0 0 0 client-output-buffer-limit slave 256mb 64mb 60 client-output-buffer-limit pubsub 32mb 8mb 60 # Redis calls an internal function to perform many background tasks, like # closing connections of clients in timeot, purging expired keys that are # never requested, and so forth. # # Not all tasks are perforemd with the same frequency, but Redis checks for # tasks to perform according to the specified "hz" value. # # By default "hz" is set to 10. Raising the value will use more CPU when # Redis is idle, but at the same time will make Redis more responsive when # there are many keys expiring at the same time, and timeouts may be # handled with more precision. # # The range is between 1 and 500, however a value over 100 is usually not # a good idea. Most users should use the default of 10 and raise this up to # 100 only in environments where very low latency is required. hz 10 # When a child rewrites the AOF file, if the following option is enabled # the file will be fsync-ed every 32 MB of data generated. This is useful # in order to commit the file to the disk more incrementally and avoid # big latency spikes. aof-rewrite-incremental-fsync yes ################################## INCLUDES ################################### # Include one or more other config files here. This is useful if you # have a standard template that goes to all Redis server but also need # to customize a few per-server settings. Include files can include # other files, so use this wisely. # # include /path/to/local.conf # include /path/to/other.conf
Python爬取网站解压问题
# Python爬取网站解压问题 刚开始是不用解压就能进行utf-8解码,后来发现时行时不行,按照网上的办法查询后发现是因为被gzip压缩,不清楚为什么一开始可以正常解码,现在进行gzip解压,代码如下: ``` from urllib import request import gzip # 打开网页 response = request.urlopen("https://www.csdn.net/") # 读取网页信息 html = response.read() # decode()命令将网页的信息进行解码 html = gzip.decompress(html).decode('utf-8') print(html) ``` 发现以下问题: ``` Traceback (most recent call last): File "C:/Users/ASUS/Desktop/爬虫/test1.py", line 9, in <module> html = gzip.decompress(html).decode('utf-8') File "C:\Users\ASUS\AppData\Local\Programs\Python\Python37-32\lib\gzip.py", line 532, in decompress return f.read() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python37-32\lib\gzip.py", line 276, in read return self._buffer.read(size) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python37-32\lib\gzip.py", line 463, in read if not self._read_gzip_header(): File "C:\Users\ASUS\AppData\Local\Programs\Python\Python37-32\lib\gzip.py", line 411, in _read_gzip_header raise OSError('Not a gzipped file (%r)' % magic) OSError: Not a gzipped file (b'\n') ```
tracert程序编译成功运行后,无法正常发送接收包,输出结果只有123456789101112131415161718192021222324252627282930,不显示详细情况,单步运行后发现接收发送包的部分没执行
![图片说明](https://img-ask.csdn.net/upload/201911/30/1575117089_191288.jpg) #include <iostream> #include <winsock2.h> #include <ws2tcpip.h> using namespace std; #pragma comment(lib, "Ws2_32.lib") //IP报头 typedef struct IP_HEADER { unsigned char hdr_len:4; //4位头部长度 unsigned char version:4; //4位版本号 unsigned char tos; //8位服务类型 unsigned short total_len; //16位总长度 unsigned short identifier; //16位标识符 unsigned short frag_and_flags; //3位标志加13位片偏移 unsigned char ttl; //8位生存时间 unsigned char protocol; //8位上层协议号 unsigned short checksum; //16位校验和 unsigned long sourceIP; //32位源IP地址 unsigned long destIP; //32位目的IP地址 } IP_HEADER; //ICMP报头 typedef struct ICMP_HEADER { BYTE type; //8位类型字段 BYTE code; //8位代码字段 USHORT cksum; //16位校验和 USHORT id; //16位标识符 USHORT seq; //16位序列号 } ICMP_HEADER; //报文解码结构 typedef struct DECODE_RESULT { USHORT usSeqNo; //序列号 DWORD dwRoundTripTime; //往返时间 in_addr dwIPaddr; //返回报文的IP地址 }DECODE_RESULT; //计算网际校验和函数 USHORT checksum( USHORT *pBuf, int iSize ) { unsigned long cksum = 0; while( iSize > 1 ) { cksum += *pBuf++; iSize -= sizeof(USHORT); } if( iSize )//如果 iSize 为正,即为奇数个字节 { cksum += *(UCHAR *)pBuf; //则在末尾补上一个字节,使之有偶数个字节 } cksum = ( cksum >> 16 ) + ( cksum&0xffff ); cksum += ( cksum >> 16 ); return (USHORT)( ~cksum ); } //对数据包进行解码 BOOL DecodeIcmpResponse(char * pBuf, int iPacketSize, DECODE_RESULT &DecodeResult, BYTE ICMP_ECHO_REPLY, BYTE ICMP_TIMEOUT) { //检查数据报大小的合法性 IP_HEADER* pIpHdr = ( IP_HEADER* )pBuf; int iIpHdrLen = pIpHdr->hdr_len * 4; //ip报头的长度是以4字节为单位的 //若数据包大小 小于 IP报头 + ICMP报头,则数据报大小不合法 if ( iPacketSize < ( int )( iIpHdrLen + sizeof( ICMP_HEADER ) ) ) return FALSE; //根据ICMP报文类型提取ID字段和序列号字段 ICMP_HEADER *pIcmpHdr = ( ICMP_HEADER * )( pBuf + iIpHdrLen );//ICMP报头 = 接收到的缓冲数据 + IP报头 USHORT usID, usSquNo; if( pIcmpHdr->type == ICMP_ECHO_REPLY ) //ICMP回显应答报文 { usID = pIcmpHdr->id; //报文ID usSquNo = pIcmpHdr->seq; //报文序列号 } else if( pIcmpHdr->type == ICMP_TIMEOUT )//ICMP超时差错报文 { char * pInnerIpHdr = pBuf + iIpHdrLen + sizeof( ICMP_HEADER ); //载荷中的IP头 int iInnerIPHdrLen = ( ( IP_HEADER * )pInnerIpHdr )->hdr_len * 4; //载荷中的IP头长 ICMP_HEADER * pInnerIcmpHdr = ( ICMP_HEADER * )( pInnerIpHdr + iInnerIPHdrLen );//载荷中的ICMP头 usID = pInnerIcmpHdr->id; //报文ID usSquNo = pInnerIcmpHdr->seq; //序列号 } else { return false; } //检查ID和序列号以确定收到期待数据报 if( usID != ( USHORT )GetCurrentProcessId() || usSquNo != DecodeResult.usSeqNo ) { return false; } //记录IP地址并计算往返时间 DecodeResult.dwIPaddr.s_addr = pIpHdr->sourceIP; DecodeResult.dwRoundTripTime = GetTickCount() - DecodeResult.dwRoundTripTime; //处理正确收到的ICMP数据报 if ( pIcmpHdr->type == ICMP_ECHO_REPLY || pIcmpHdr->type == ICMP_TIMEOUT ) { //输出往返时间信息 if(DecodeResult.dwRoundTripTime) cout<<" "<<DecodeResult.dwRoundTripTime<<"ms"<<flush; else cout<<" "<<"<1ms"<<flush; } return true; } void main() { //初始化Windows sockets网络环境 WSADATA wsa; WSAStartup( MAKEWORD(2,2), &wsa ); char IpAddress[255]; cout<<"请输入一个IP地址或域名:"; cin>>IpAddress; //得到IP地址 u_long ulDestIP = inet_addr( IpAddress ); //转换不成功时按域名解析 if( ulDestIP == INADDR_NONE ) { hostent * pHostent = gethostbyname( IpAddress ); if( pHostent ) { ulDestIP = ( *( in_addr* )pHostent->h_addr).s_addr; } else { cout<<"输入的IP地址或域名无效!"<<endl; WSACleanup(); return; } } cout<<"Tracing roote to "<<IpAddress<<" with a maximum of 30 hops.\n"<<endl; //填充目的端socket地址 sockaddr_in destSockAddr; ZeroMemory( &destSockAddr, sizeof( sockaddr_in ) ); destSockAddr.sin_family = AF_INET; destSockAddr.sin_addr.s_addr = ulDestIP; //创建原始套接字 SOCKET sockRaw = WSASocket( AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, WSA_FLAG_OVERLAPPED ); //超时时间 int iTimeout = 3000; //设置接收超时时间 setsockopt( sockRaw, SOL_SOCKET, SO_RCVTIMEO, (char *)&iTimeout, sizeof( iTimeout ) ); //设置发送超时时间 setsockopt(sockRaw,SOL_SOCKET,SO_SNDTIMEO,(char *)&iTimeout,sizeof(iTimeout)); //构造ICMP回显请求消息,并以TTL递增的顺序发送报文 //ICMP类型字段 const BYTE ICMP_ECHO_REQUEST = 8; //请求回显 const BYTE ICMP_ECHO_REPLY = 0; //回显应答 const BYTE ICMP_TIMEOUT = 11; //传输超时 //其他常量定义 const int DEF_ICMP_DATA_SIZE = 32; //ICMP报文默认数据字段长度 const int MAX_ICMP_PACKET_SIZE = 1024; //ICMP报文最大长度(包括报头) const DWORD DEF_ICMP_TIMEOUT = 3000; //回显应答超时时间 const int DEF_MAX_HOP = 30; //最大跳站数 //填充ICMP报文中每次发送时不变的字段 char IcmpSendBuf[ sizeof( ICMP_HEADER ) + DEF_ICMP_DATA_SIZE ];//发送缓冲区 memset( IcmpSendBuf, 0, sizeof( IcmpSendBuf ) ); //初始化发送缓冲区 char IcmpRecvBuf[ MAX_ICMP_PACKET_SIZE ]; //接收缓冲区 memset( IcmpRecvBuf, 0, sizeof( IcmpRecvBuf ) ); //初始化接收缓冲区 ICMP_HEADER * pIcmpHeader = ( ICMP_HEADER* )IcmpSendBuf; pIcmpHeader->type = ICMP_ECHO_REQUEST; //类型为请求回显 pIcmpHeader->code = 0; //代码字段为0 pIcmpHeader->id = (USHORT)GetCurrentProcessId(); //ID字段为当前进程号 memset( IcmpSendBuf + sizeof( ICMP_HEADER ), 'E', DEF_ICMP_DATA_SIZE );//数据字段 USHORT usSeqNo = 0; //ICMP报文序列号 int iTTL = 1; //TTL初始值为1 BOOL bReachDestHost = FALSE; //循环退出标志 int iMaxHot = DEF_MAX_HOP; //循环的最大次数 DECODE_RESULT DecodeResult; //传递给报文解码函数的结构化参数 while( !bReachDestHost && iMaxHot-- ) { //设置IP报头的TTL字段 setsockopt( sockRaw, IPPROTO_IP, IP_TTL, (char *)&iTTL, sizeof(iTTL) ); cout<<iTTL<<flush; //输出当前序号,flush表示将缓冲区的内容马上送进cout,把输出缓冲区刷新 //填充ICMP报文中每次发送变化的字段 ((ICMP_HEADER *)IcmpSendBuf)->cksum = 0; //校验和先置为0 ((ICMP_HEADER *)IcmpSendBuf)->seq = htons(usSeqNo++); //填充序列号 ((ICMP_HEADER *)IcmpSendBuf)->cksum = checksum( ( USHORT * )IcmpSendBuf, sizeof( ICMP_HEADER ) + DEF_ICMP_DATA_SIZE ); //计算校验和 //记录序列号和当前时间 DecodeResult.usSeqNo = ( ( ICMP_HEADER* )IcmpSendBuf )->seq; //当前序号 DecodeResult.dwRoundTripTime = GetTickCount(); //当前时间 //发送TCP回显请求信息 sendto( sockRaw, IcmpSendBuf, sizeof(IcmpSendBuf), 0, (sockaddr*)&destSockAddr, sizeof(destSockAddr) ); //接收ICMP差错报文并进行解析处理 sockaddr_in from; //对端socket地址 int iFromLen = sizeof(from);//地址结构大小 int iReadDataLen; //接收数据长度 while(1) { //接收数据 iReadDataLen = recvfrom( sockRaw, IcmpRecvBuf, MAX_ICMP_PACKET_SIZE, 0, (sockaddr*)&from, &iFromLen ); if( iReadDataLen != SOCKET_ERROR )//有数据到达 { //对数据包进行解码 if(DecodeIcmpResponse( IcmpRecvBuf, iReadDataLen, DecodeResult, ICMP_ECHO_REPLY, ICMP_TIMEOUT ) ) { //到达目的地,退出循环 if( DecodeResult.dwIPaddr.s_addr == destSockAddr.sin_addr.s_addr ) bReachDestHost = true; //输出IP地址 cout<<'\t'<<inet_ntoa( DecodeResult.dwIPaddr )<<endl; break; } } else if( WSAGetLastError() == WSAETIMEDOUT ) //接收超时,输出*号 { cout<<" *"<<'\t'<<"Request timed out."<<endl; break; } else { break; } } iTTL++; //递增TTL值 } }
HTTP Status 500 – Internal Server Error(jspmaker生成,tomcat实现)
内容是用Jspmaker把数据库表生成jsp,然后用tomcat,结果出现了以下问题 网站报错代码如下: HTTP Status 500 – Internal Server ErrorType 异常报告 消息 在 [146] 行处理 [/jspmoon/customerlist.jsp] 时发生异常 描述 服务器遇到一个意外的情况,阻止它完成请求。 Exception org.apache.jasper.JasperException: 在 [146] 行处理 [/jspmoon/customerlist.jsp] 时发生异常 143: // Open Connection to the database 144: try{ 145: Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); 146: ResultSet rs = null; 147: // Build SQL 148: String strsql = "SELECT * FROM `customer`"; 149: whereClause = ""; Stacktrace: org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:617) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:514) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) Root Cause java.lang.NullPointerException org.apache.jsp.jspmoon.customerlist_jsp._jspService(customerlist_jsp.java:585) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ):注意 主要问题的全部 stack 信息可以在 server logs 里查看 Apache Tomcat/8.5.50 jsp代码: <%@ page session="true" buffer="16kb" import="java.sql.*,java.util.*,java.text.*"%> <%@ page contentType="text/html; charset=UTF-8" %> <% response.setDateHeader("Expires", 0); // date in the past response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // HTTP/1.1 response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.addHeader("Pragma", "no-cache"); // HTTP/1.0 %> <% Locale locale = Locale.getDefault(); response.setLocale(locale);%> <% session.setMaxInactiveInterval(30*60); %> <%@ include file="db.jsp" %> <%@ include file="jspmkrfn.jsp" %> <% int displayRecs = 20; int recRange = 10; %> <% String tmpfld = null; String escapeString = "\\\\'"; String dbwhere = ""; String masterdetailwhere = ""; String searchwhere = ""; String a_search = ""; String b_search = ""; String whereClause = ""; int startRec = 0, stopRec = 0, totalRecs = 0, recCount = 0; %> <% // Get search criteria for basic search String pSearch = request.getParameter("psearch"); String pSearchType = request.getParameter("psearchtype"); if (pSearch != null && pSearch.length() > 0) { pSearch = pSearch.replaceAll("'",escapeString); if (pSearchType != null && pSearchType.length() > 0) { while (pSearch.indexOf(" ") > 0) { pSearch = pSearch.replaceAll(" ", " "); } String [] arpSearch = pSearch.trim().split(" "); for (int i = 0; i < arpSearch.length; i++){ String kw = arpSearch[i].trim(); b_search = b_search + "("; b_search = b_search + "`C_NAME` LIKE '%" + kw + "%' OR "; b_search = b_search + "`C_ADDRESS` LIKE '%" + kw + "%' OR "; b_search = b_search + "`C_PHONE` LIKE '%" + kw + "%' OR "; b_search = b_search + "`C_MATSEGMENT` LIKE '%" + kw + "%' OR "; b_search = b_search + "`C_COMMENT` LIKE '%" + kw + "%' OR "; if (b_search.substring(b_search.length()-4,b_search.length()).equals(" OR ")) { b_search = b_search.substring(0,b_search.length()-4);} b_search = b_search + ") " + pSearchType + " "; } }else{ b_search = b_search + "`C_NAME` LIKE '%" + pSearch + "%' OR "; b_search = b_search + "`C_ADDRESS` LIKE '%" + pSearch + "%' OR "; b_search = b_search + "`C_PHONE` LIKE '%" + pSearch + "%' OR "; b_search = b_search + "`C_MATSEGMENT` LIKE '%" + pSearch + "%' OR "; b_search = b_search + "`C_COMMENT` LIKE '%" + pSearch + "%' OR "; } } if (b_search.length() > 4 && b_search.substring(b_search.length()-4,b_search.length()).equals(" OR ")) {b_search = b_search.substring(0, b_search.length()-4);} if (b_search.length() > 5 && b_search.substring(b_search.length()-5,b_search.length()).equals(" AND ")) {b_search = b_search.substring(0, b_search.length()-5);} %> <% // Build search criteria if (a_search != null && a_search.length() > 0) { searchwhere = a_search; // Advanced search }else if (b_search != null && b_search.length() > 0) { searchwhere = b_search; // Basic search } // Save search criteria if (searchwhere != null && searchwhere.length() > 0) { session.setAttribute("customer_searchwhere", searchwhere); startRec = 1; // Reset start record counter (new search) session.setAttribute("customer_REC", new Integer(startRec)); }else{ if (session.getAttribute("customer_searchwhere") != null) searchwhere = (String) session.getAttribute("customer_searchwhere"); } %> <% // Get clear search cmd startRec = 0; if (request.getParameter("cmd") != null && request.getParameter("cmd").length() > 0) { String cmd = request.getParameter("cmd"); if (cmd.toUpperCase().equals("RESET")) { searchwhere = ""; // Reset search criteria session.setAttribute("customer_searchwhere", searchwhere); }else if (cmd.toUpperCase().equals("RESETALL")) { searchwhere = ""; // Reset search criteria session.setAttribute("customer_searchwhere", searchwhere); } startRec = 1; // Reset start record counter (reset command) session.setAttribute("customer_REC", new Integer(startRec)); } // Build dbwhere if (masterdetailwhere != null && masterdetailwhere.length() > 0) { dbwhere = dbwhere + "(" + masterdetailwhere + ") AND "; } if (searchwhere != null && searchwhere.length() > 0) { dbwhere = dbwhere + "(" + searchwhere + ") AND "; } if (dbwhere != null && dbwhere.length() > 5) { dbwhere = dbwhere.substring(0, dbwhere.length()-5); // Trim rightmost AND } %> <% // Load Default Order String DefaultOrder = ""; String DefaultOrderType = ""; // No Default Filter String DefaultFilter = ""; // Check for an Order parameter String OrderBy = request.getParameter("order"); if (OrderBy != null && OrderBy.length() > 0) { if (session.getAttribute("customer_OB") != null && ((String) session.getAttribute("customer_OB")).equals(OrderBy)) { // Check if an ASC/DESC toggle is required if (((String) session.getAttribute("customer_OT")).equals("ASC")) { session.setAttribute("customer_OT", "DESC"); }else{ session.setAttribute("customer_OT", "ASC"); } }else{ session.setAttribute("customer_OT", "ASC"); } session.setAttribute("customer_OB", OrderBy); session.setAttribute("customer_REC", new Integer(1)); }else{ OrderBy = (String) session.getAttribute("customer_OB"); if (OrderBy == null || OrderBy.length() == 0) { OrderBy = DefaultOrder; session.setAttribute("customer_OB", OrderBy); session.setAttribute("customer_OT", DefaultOrderType); } } // Open Connection to the database try{ Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = null; // Build SQL String strsql = "SELECT * FROM `customer`"; whereClause = ""; if (DefaultFilter.length() > 0) { whereClause = whereClause + "(" + DefaultFilter + ") AND "; } if (dbwhere.length() > 0) { whereClause = whereClause + "(" + dbwhere + ") AND "; } if (whereClause.length() > 5 && whereClause.substring(whereClause.length()-5, whereClause.length()).equals(" AND ")) { whereClause = whereClause.substring(0, whereClause.length()-5); } if (whereClause.length() > 0) { strsql = strsql + " WHERE " + whereClause; } if (OrderBy != null && OrderBy.length() > 0) { strsql = strsql + " ORDER BY `" + OrderBy + "` " + (String) session.getAttribute("customer_OT"); } //out.println(strsql); rs = stmt.executeQuery(strsql); rs.last(); totalRecs = rs.getRow(); rs.beforeFirst(); startRec = 0; int pageno = 0; // Check for a START parameter if (request.getParameter("start") != null && Integer.parseInt(request.getParameter("start")) > 0) { startRec = Integer.parseInt(request.getParameter("start")); session.setAttribute("customer_REC", new Integer(startRec)); }else if (request.getParameter("pageno") != null && Integer.parseInt(request.getParameter("pageno")) > 0) { pageno = Integer.parseInt(request.getParameter("pageno")); if (IsNumeric(request.getParameter("pageno"))) { startRec = (pageno-1)*displayRecs+1; if (startRec <= 0) { startRec = 1; }else if (startRec >= ((totalRecs-1)/displayRecs)*displayRecs+1) { startRec = ((totalRecs-1)/displayRecs)*displayRecs+1; } session.setAttribute("customer_REC", new Integer(startRec)); }else { startRec = ((Integer) session.getAttribute("customer_REC")).intValue(); if (startRec <= 0) { startRec = 1; // Reset start record counter session.setAttribute("customer_REC", new Integer(startRec)); } } }else{ if (session.getAttribute("customer_REC") != null) startRec = ((Integer) session.getAttribute("customer_REC")).intValue(); if (startRec==0) { startRec = 1; //Reset start record counter session.setAttribute("customer_REC", new Integer(startRec)); } } %> <%@ include file="header.jsp" %> <p><span class="jspmaker">TABLE: customer</span></p> <form action="customerlist.jsp"> <table border="0" cellspacing="0" cellpadding="4"> <tr> <td><span class="jspmaker">Quick Search (*)</span></td> <td><span class="jspmaker"> <input type="text" name="psearch" size="20"> <input type="Submit" name="Submit" value="GO"> &nbsp;&nbsp;<a href="customerlist.jsp?cmd=reset">Show all</a> </span></td> </tr> <tr><td>&nbsp;</td><td><span class="jspmaker"><input type="radio" name="psearchtype" value="" checked>Exact phrase&nbsp;&nbsp;<input type="radio" name="psearchtype" value="AND">All words&nbsp;&nbsp;<input type="radio" name="psearchtype" value="OR">Any word</span></td></tr> </table> </form> <form method="post"> <table border="0" cellspacing="1" cellpadding="4" bgcolor="#CCCCCC"> <tr bgcolor="#594FBF"> <td><span class="jspmaker" style="color: #FFFFFF;"> <a href="customerlist.jsp?order=<%= java.net.URLEncoder.encode("C_CUSTKEY","UTF-8") %>" style="color: #FFFFFF;">C CUSTKEY&nbsp;<% if (OrderBy != null && OrderBy.equals("C_CUSTKEY")) { %><span class="ewTableOrderIndicator"><% if (((String) session.getAttribute("customer_OT")).equals("ASC")) {%>5<% }else if (((String) session.getAttribute("customer_OT")).equals("DESC")) { %>6<% } %></span><% } %></a> </span></td> <td><span class="jspmaker" style="color: #FFFFFF;"> <a href="customerlist.jsp?order=<%= java.net.URLEncoder.encode("C_NAME","UTF-8") %>" style="color: #FFFFFF;">C NAME&nbsp;(*)<% if (OrderBy != null && OrderBy.equals("C_NAME")) { %><span class="ewTableOrderIndicator"><% if (((String) session.getAttribute("customer_OT")).equals("ASC")) {%>5<% }else if (((String) session.getAttribute("customer_OT")).equals("DESC")) { %>6<% } %></span><% } %></a> </span></td> <td><span class="jspmaker" style="color: #FFFFFF;"> <a href="customerlist.jsp?order=<%= java.net.URLEncoder.encode("C_ADDRESS","UTF-8") %>" style="color: #FFFFFF;">C ADDRESS&nbsp;(*)<% if (OrderBy != null && OrderBy.equals("C_ADDRESS")) { %><span class="ewTableOrderIndicator"><% if (((String) session.getAttribute("customer_OT")).equals("ASC")) {%>5<% }else if (((String) session.getAttribute("customer_OT")).equals("DESC")) { %>6<% } %></span><% } %></a> </span></td> <td><span class="jspmaker" style="color: #FFFFFF;"> <a href="customerlist.jsp?order=<%= java.net.URLEncoder.encode("C_NATIONKEY","UTF-8") %>" style="color: #FFFFFF;">C NATIONKEY&nbsp;<% if (OrderBy != null && OrderBy.equals("C_NATIONKEY")) { %><span class="ewTableOrderIndicator"><% if (((String) session.getAttribute("customer_OT")).equals("ASC")) {%>5<% }else if (((String) session.getAttribute("customer_OT")).equals("DESC")) { %>6<% } %></span><% } %></a> </span></td> <td><span class="jspmaker" style="color: #FFFFFF;"> <a href="customerlist.jsp?order=<%= java.net.URLEncoder.encode("C_PHONE","UTF-8") %>" style="color: #FFFFFF;">C PHONE&nbsp;(*)<% if (OrderBy != null && OrderBy.equals("C_PHONE")) { %><span class="ewTableOrderIndicator"><% if (((String) session.getAttribute("customer_OT")).equals("ASC")) {%>5<% }else if (((String) session.getAttribute("customer_OT")).equals("DESC")) { %>6<% } %></span><% } %></a> </span></td> <td><span class="jspmaker" style="color: #FFFFFF;"> <a href="customerlist.jsp?order=<%= java.net.URLEncoder.encode("C_ACCTBAL","UTF-8") %>" style="color: #FFFFFF;">C ACCTBAL&nbsp;<% if (OrderBy != null && OrderBy.equals("C_ACCTBAL")) { %><span class="ewTableOrderIndicator"><% if (((String) session.getAttribute("customer_OT")).equals("ASC")) {%>5<% }else if (((String) session.getAttribute("customer_OT")).equals("DESC")) { %>6<% } %></span><% } %></a> </span></td> <td><span class="jspmaker" style="color: #FFFFFF;"> <a href="customerlist.jsp?order=<%= java.net.URLEncoder.encode("C_MATSEGMENT","UTF-8") %>" style="color: #FFFFFF;">C MATSEGMENT&nbsp;(*)<% if (OrderBy != null && OrderBy.equals("C_MATSEGMENT")) { %><span class="ewTableOrderIndicator"><% if (((String) session.getAttribute("customer_OT")).equals("ASC")) {%>5<% }else if (((String) session.getAttribute("customer_OT")).equals("DESC")) { %>6<% } %></span><% } %></a> </span></td> <td><span class="jspmaker" style="color: #FFFFFF;"> <a href="customerlist.jsp?order=<%= java.net.URLEncoder.encode("C_COMMENT","UTF-8") %>" style="color: #FFFFFF;">C COMMENT&nbsp;(*)<% if (OrderBy != null && OrderBy.equals("C_COMMENT")) { %><span class="ewTableOrderIndicator"><% if (((String) session.getAttribute("customer_OT")).equals("ASC")) {%>5<% }else if (((String) session.getAttribute("customer_OT")).equals("DESC")) { %>6<% } %></span><% } %></a> </span></td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <% // Avoid starting record > total records if (startRec > totalRecs) { startRec = totalRecs; } // Set the last record to display stopRec = startRec + displayRecs - 1; // Move to first record directly for performance reason recCount = startRec - 1; if (rs.next()) { rs.first(); rs.relative(startRec - 1); } long recActual = 0; if (startRec == 1) rs.beforeFirst(); else rs.previous(); while (rs.next() && recCount < stopRec) { recCount++; if (recCount >= startRec) { recActual++; %> <% String bgcolor = "#FFFFFF"; // Set row color %> <% if (recCount%2 != 0) { // Display alternate color for rows bgcolor = "#F5F5F5"; } %> <% String x_C_CUSTKEY = ""; String x_C_NAME = ""; String x_C_ADDRESS = ""; String x_C_NATIONKEY = ""; String x_C_PHONE = ""; String x_C_ACCTBAL = ""; String x_C_MATSEGMENT = ""; String x_C_COMMENT = ""; // Load Key for record String key = ""; key = String.valueOf(rs.getLong("C_CUSTKEY")); // C_CUSTKEY x_C_CUSTKEY = String.valueOf(rs.getLong("C_CUSTKEY")); // C_NAME if (rs.getString("C_NAME") != null){ x_C_NAME = rs.getString("C_NAME"); }else{ x_C_NAME = ""; } // C_ADDRESS if (rs.getString("C_ADDRESS") != null){ x_C_ADDRESS = rs.getString("C_ADDRESS"); }else{ x_C_ADDRESS = ""; } // C_NATIONKEY x_C_NATIONKEY = String.valueOf(rs.getLong("C_NATIONKEY")); // C_PHONE if (rs.getString("C_PHONE") != null){ x_C_PHONE = rs.getString("C_PHONE"); }else{ x_C_PHONE = ""; } // C_ACCTBAL x_C_ACCTBAL = String.valueOf(rs.getDouble("C_ACCTBAL")); // C_MATSEGMENT if (rs.getString("C_MATSEGMENT") != null){ x_C_MATSEGMENT = rs.getString("C_MATSEGMENT"); }else{ x_C_MATSEGMENT = ""; } // C_COMMENT if (rs.getString("C_COMMENT") != null){ x_C_COMMENT = rs.getString("C_COMMENT"); }else{ x_C_COMMENT = ""; } %> <tr bgcolor="<%= bgcolor %>"> <td><span class="jspmaker"><% out.print(x_C_CUSTKEY); %></span>&nbsp;</td> <td><span class="jspmaker"><% out.print(x_C_NAME); %></span>&nbsp;</td> <td><span class="jspmaker"><% out.print(x_C_ADDRESS); %></span>&nbsp;</td> <td><span class="jspmaker"><% out.print(x_C_NATIONKEY); %></span>&nbsp;</td> <td><span class="jspmaker"><% out.print(x_C_PHONE); %></span>&nbsp;</td> <td><span class="jspmaker"><% out.print(x_C_ACCTBAL); %></span>&nbsp;</td> <td><span class="jspmaker"><% out.print(x_C_MATSEGMENT); %></span>&nbsp;</td> <td><span class="jspmaker"><% out.print(x_C_COMMENT); %></span>&nbsp;</td> <td><span class="jspmaker"><a href="<% key = rs.getString("C_CUSTKEY"); if (key != null && key.length() > 0) { out.print("customerview.jsp?key=" + java.net.URLEncoder.encode(key,"UTF-8")); }else{ out.print("javascript:alert('Invalid Record! Key is null');"); } %>">View</a></span></td> <td><span class="jspmaker"><a href="<% key = rs.getString("C_CUSTKEY"); if (key != null && key.length() > 0) { out.print("customeredit.jsp?key=" + java.net.URLEncoder.encode(key,"UTF-8")); }else{ out.print("javascript:alert('Invalid Record! Key is null');"); } %>">Edit</a></span></td> <td><span class="jspmaker"><a href="<% key = rs.getString("C_CUSTKEY"); if (key != null && key.length() > 0) { out.print("customeradd.jsp?key=" + java.net.URLEncoder.encode(key,"UTF-8")); }else{ out.print("javascript:alert('Invalid Record! Key is null');"); } %>">Copy</a></span></td> <td><span class="jspmaker"><a href="<% key = rs.getString("C_CUSTKEY"); if (key != null && key.length() > 0) { out.print("customerdelete.jsp?key=" + java.net.URLEncoder.encode(key,"UTF-8")); }else{ out.print("javascript:alert('Invalid Record! Key is null');"); } %>">Delete</a></span></td> </tr> <% // } } } %> </table> </form> <% // Close recordset and connection rs.close(); rs = null; stmt.close(); stmt = null; conn.close(); conn = null; }catch(SQLException ex){ out.println(ex.toString()); } %> <table border="0" cellspacing="0" cellpadding="10"><tr><td> <% boolean rsEof = false; if (totalRecs > 0) { rsEof = (totalRecs < (startRec + displayRecs)); int PrevStart = startRec - displayRecs; if (PrevStart < 1) { PrevStart = 1;} int NextStart = startRec + displayRecs; if (NextStart > totalRecs) { NextStart = startRec;} int LastStart = ((totalRecs-1)/displayRecs)*displayRecs+1; %> <form> <table border="0" cellspacing="0" cellpadding="0"><tr><td><span class="jspmaker">Page</span>&nbsp;</td> <!--first page button--> <% if (startRec==1) { %> <td><img src="images/firstdisab.gif" alt="First" width="20" height="15" border="0"></td> <% }else{ %> <td><a href="customerlist.jsp?start=1"><img src="images/first.gif" alt="First" width="20" height="15" border="0"></a></td> <% } %> <!--previous page button--> <% if (PrevStart == startRec) { %> <td><img src="images/prevdisab.gif" alt="Previous" width="20" height="15" border="0"></td> <% }else{ %> <td><a href="customerlist.jsp?start=<%=PrevStart%>"><img src="images/prev.gif" alt="Previous" width="20" height="15" border="0"></a></td> <% } %> <!--current page number--> <td><input type="text" name="pageno" value="<%=(startRec-1)/displayRecs+1%>" size="4"></td> <!--next page button--> <% if (NextStart == startRec) { %> <td><img src="images/nextdisab.gif" alt="Next" width="20" height="15" border="0"></td> <% }else{ %> <td><a href="customerlist.jsp?start=<%=NextStart%>"><img src="images/next.gif" alt="Next" width="20" height="15" border="0"></a></td> <% } %> <!--last page button--> <% if (LastStart == startRec) { %> <td><img src="images/lastdisab.gif" alt="Last" width="20" height="15" border="0"></td> <% }else{ %> <td><a href="customerlist.jsp?start=<%=LastStart%>"><img src="images/last.gif" alt="Last" width="20" height="15" border="0"></a></td> <% } %> <td><a href="customeradd.jsp"><img src="images/addnew.gif" alt="Add new" width="20" height="15" border="0"></a></td> <td><span class="jspmaker">&nbsp;of <%=(totalRecs-1)/displayRecs+1%></span></td> </td></tr></table> </form> <% if (startRec > totalRecs) { startRec = totalRecs;} stopRec = startRec + displayRecs - 1; recCount = totalRecs - 1; if (rsEof) { recCount = totalRecs;} if (stopRec > recCount) { stopRec = recCount;} %> <span class="jspmaker">Records <%= startRec %> to <%= stopRec %> of <%= totalRecs %></span> <% }else{ %> <span class="jspmaker">No records found</span> <p> <a href="customeradd.jsp"><img src="images/addnew.gif" alt="Add new" width="20" height="15" border="0"></a> </p> <% } %> </td></tr></table> <%@ include file="footer.jsp" %>
新网VPS没有绑定域名 不能通过ip访问?
新网vps, redhat, apache ssh没有问题,防火墙设置把所有的都关掉了(用setup命令操作的) **没有绑定域名,因为域名还没选好** netstat也查过了,两个端口都在 netstat -tulpn | grep :80 netstat -tulpn | grep :8080 ssh 后,使用下面这个命令可以得到index.html中的内容, GET http://我的ip/index.html GET http://我的ip:8080/index.html (启动的另一个apache instance,端口设置为8080) 但是浏览器中输入http://我的ip/index.html 就没有反应 请问Linux和apache配置方面还有什么要注意的? 是不是新网、ISP提供商禁止了ip方式访问?(因为我看到国内外论坛上都提到过服务商会吧IP问80端口禁止) 下面是httpd.conf # # This is the main Apache server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.2/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.2/mod/directives.html> # for a discussion of each configuration directive. # # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # The configuration directives are grouped into three basic sections: # 1. Directives that control the operation of the Apache server process as a # whole (the 'global environment'). # 2. Directives that define the parameters of the 'main' or 'default' server, # which responds to requests that aren't handled by a virtual host. # These directives also provide default values for the settings # of all virtual hosts. # 3. Settings for virtual hosts, which allow Web requests to be sent to # different IP addresses or hostnames and have them handled by the # same Apache server process. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "logs/foo.log" # with ServerRoot set to "/etc/httpd" will be interpreted by the # server as "/etc/httpd/logs/foo.log". # ### Section 1: Global Environment # # The directives in this section affect the overall operation of Apache, # such as the number of concurrent requests it can handle or where it # can find its configuration files. # # # Don't give away too much information about all the subcomponents # we are running. Comment out this line if you don't mind remote sites # finding out what major optional modules you are running ServerTokens OS # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # NOTE! If you intend to place this on an NFS (or otherwise network) # mounted filesystem then please read the LockFile documentation # (available at <URL:http://httpd.apache.org/docs/2.2/mod/mpm_common.html#lockfile>); # you will save yourself a lot of trouble. # # Do NOT add a slash at the end of the directory path. # ServerRoot "/etc/httpd" # # PidFile: The file in which the server should record its process # identification number when it starts. # PidFile run/httpd.pid # # Timeout: The number of seconds before receives and sends time out. # Timeout 120 # # KeepAlive: Whether or not to allow persistent connections (more than # one request per connection). Set to "Off" to deactivate. # KeepAlive Off # # MaxKeepAliveRequests: The maximum number of requests to allow # during a persistent connection. Set to 0 to allow an unlimited amount. # We recommend you leave this number high, for maximum performance. # MaxKeepAliveRequests 100 # # KeepAliveTimeout: Number of seconds to wait for the next request from the # same client on the same connection. # KeepAliveTimeout 15 ## ## Server-Pool Size Regulation (MPM specific) ## # prefork MPM # StartServers: number of server processes to start # MinSpareServers: minimum number of server processes which are kept spare # MaxSpareServers: maximum number of server processes which are kept spare # ServerLimit: maximum value for MaxClients for the lifetime of the server # MaxClients: maximum number of server processes allowed to start # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule prefork.c> StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxClients 256 MaxRequestsPerChild 4000 </IfModule> # worker MPM # StartServers: initial number of server processes to start # MaxClients: maximum number of simultaneous client connections # MinSpareThreads: minimum number of worker threads which are kept spare # MaxSpareThreads: maximum number of worker threads which are kept spare # ThreadsPerChild: constant number of worker threads in each server process # MaxRequestsPerChild: maximum number of requests a server process serves <IfModule worker.c> StartServers 2 MaxClients 150 MinSpareThreads 25 MaxSpareThreads 75 ThreadsPerChild 25 MaxRequestsPerChild 0 </IfModule> # # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, in addition to the default. See also the <VirtualHost> # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses (0.0.0.0) # #Listen 12.34.56.78:80 Listen 80 # # Dynamic Shared Object (DSO) Support # # To be able to use the functionality of a module which was built as a DSO you # have to place corresponding `LoadModule' lines at this location so the # directives contained in it are actually available _before_ they are used. # Statically compiled modules (those listed by `httpd -l') do not need # to be loaded here. # # Example: # LoadModule foo_module modules/mod_foo.so # LoadModule auth_basic_module modules/mod_auth_basic.so LoadModule auth_digest_module modules/mod_auth_digest.so LoadModule authn_file_module modules/mod_authn_file.so LoadModule authn_alias_module modules/mod_authn_alias.so LoadModule authn_anon_module modules/mod_authn_anon.so LoadModule authn_dbm_module modules/mod_authn_dbm.so LoadModule authn_default_module modules/mod_authn_default.so LoadModule authz_host_module modules/mod_authz_host.so LoadModule authz_user_module modules/mod_authz_user.so LoadModule authz_owner_module modules/mod_authz_owner.so LoadModule authz_groupfile_module modules/mod_authz_groupfile.so LoadModule authz_dbm_module modules/mod_authz_dbm.so LoadModule authz_default_module modules/mod_authz_default.so LoadModule ldap_module modules/mod_ldap.so LoadModule authnz_ldap_module modules/mod_authnz_ldap.so LoadModule include_module modules/mod_include.so LoadModule log_config_module modules/mod_log_config.so LoadModule logio_module modules/mod_logio.so LoadModule env_module modules/mod_env.so LoadModule ext_filter_module modules/mod_ext_filter.so LoadModule mime_magic_module modules/mod_mime_magic.so LoadModule expires_module modules/mod_expires.so LoadModule deflate_module modules/mod_deflate.so LoadModule headers_module modules/mod_headers.so LoadModule usertrack_module modules/mod_usertrack.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule mime_module modules/mod_mime.so LoadModule dav_module modules/mod_dav.so LoadModule status_module modules/mod_status.so LoadModule autoindex_module modules/mod_autoindex.so LoadModule info_module modules/mod_info.so LoadModule dav_fs_module modules/mod_dav_fs.so LoadModule vhost_alias_module modules/mod_vhost_alias.so LoadModule negotiation_module modules/mod_negotiation.so LoadModule dir_module modules/mod_dir.so LoadModule actions_module modules/mod_actions.so LoadModule speling_module modules/mod_speling.so LoadModule userdir_module modules/mod_userdir.so LoadModule alias_module modules/mod_alias.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so LoadModule proxy_ftp_module modules/mod_proxy_ftp.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule proxy_connect_module modules/mod_proxy_connect.so LoadModule cache_module modules/mod_cache.so LoadModule suexec_module modules/mod_suexec.so LoadModule disk_cache_module modules/mod_disk_cache.so LoadModule file_cache_module modules/mod_file_cache.so LoadModule mem_cache_module modules/mod_mem_cache.so LoadModule cgi_module modules/mod_cgi.so LoadModule version_module modules/mod_version.so # # The following modules are not loaded by default: # #LoadModule cern_meta_module modules/mod_cern_meta.so #LoadModule asis_module modules/mod_asis.so # # Load config files from the config directory "/etc/httpd/conf.d". # Include conf.d/*.conf # # ExtendedStatus controls whether Apache will generate "full" status # information (ExtendedStatus On) or just basic information (ExtendedStatus # Off) when the "server-status" handler is called. The default is Off. # #ExtendedStatus On # # If you wish httpd to run as a different user or group, you must run # httpd as root initially and it will switch. # # User/Group: The name (or #number) of the user/group to run httpd as. # . On SCO (ODT 3) use "User nouser" and "Group nogroup". # . On HPUX you may not be able to use shared memory as nobody, and the # suggested workaround is to create a user www and use that user. # NOTE that some kernels refuse to setgid(Group) or semctl(IPC_SET) # when the value of (unsigned)Group is above 60000; # don't use Group #-1 on these systems! # User apache Group apache ### Section 2: 'Main' server configuration # # The directives in this section set up the values used by the 'main' # server, which responds to any requests that aren't handled by a # <VirtualHost> definition. These values also provide defaults for # any <VirtualHost> containers you may define later in the file. # # All of these directives may appear inside <VirtualHost> containers, # in which case these default settings will be overridden for the # virtual host being defined. # # # ServerAdmin: Your address, where problems with the server should be # e-mailed. This address appears on some server-generated pages, such # as error documents. e.g. admin@your-domain.com # ServerAdmin root@localhost # # ServerName gives the name and port that the server uses to identify itself. # This can often be determined automatically, but we recommend you specify # it explicitly to prevent problems during startup. # # If this is not set to valid DNS name for your host, server-generated # redirections will not work. See also the UseCanonicalName directive. # # If your host doesn't have a registered DNS name, enter its IP address here. # You will have to access it by its address anyway, and this will make # redirections work in a sensible way. # #ServerName www.example.com:80 # eric add ServerName 我的ip!!!! # eric add end # # UseCanonicalName: Determines how Apache constructs self-referencing # URLs and the SERVER_NAME and SERVER_PORT variables. # When set "Off", Apache will use the Hostname and Port supplied # by the client. When set "On", Apache will use the value of the # ServerName directive. # UseCanonicalName Off # # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "/var/www/html" # # Each directory to which Apache has access can be configured with respect # to which services and features are allowed and/or disabled in that # directory (and its subdirectories). # # First, we configure the "default" to be a very restrictive set of # features. # <Directory /> Options FollowSymLinks AllowOverride None </Directory> # # Note that from this point forward you must specifically allow # particular features to be enabled - so if something's not working as # you might expect, make sure that you have specifically enabled it # below. # # # This should be changed to whatever you set DocumentRoot to. # <Directory "/var/www/html"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Order allow,deny Allow from all #Deny from all </Directory> # # UserDir: The name of the directory that is appended onto a user's home # directory if a ~user request is received. # # The path to the end user account 'public_html' directory must be # accessible to the webserver userid. This usually means that ~userid # must have permissions of 711, ~userid/public_html must have permissions # of 755, and documents contained therein must be world-readable. # Otherwise, the client will only receive a "403 Forbidden" message. # # See also: http://httpd.apache.org/docs/misc/FAQ.html#forbidden # <IfModule mod_userdir.c> # # UserDir is disabled by default since it can confirm the presence # of a username on the system (depending on home directory # permissions). # UserDir disable # # To enable requests to /~user/ to serve the user's public_html # directory, remove the "UserDir disable" line above, and uncomment # the following line instead: # #UserDir public_html </IfModule> # # Control access to UserDir directories. The following is an example # for a site where these directories are restricted to read-only. # #<Directory /home/*/public_html> # AllowOverride FileInfo AuthConfig Limit # Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec # <Limit GET POST OPTIONS> # Order allow,deny # Allow from all # </Limit> # <LimitExcept GET POST OPTIONS> # Order deny,allow # Deny from all # </LimitExcept> #</Directory> # # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # # The index.html.var file (a type-map) is used to deliver content- # negotiated documents. The MultiViews Option can be used for the # same purpose, but it is much slower. # DirectoryIndex index.html index.html.var # # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <Files ~ "^\.ht"> Order allow,deny Deny from all </Files> # # TypesConfig describes where the mime.types file (or equivalent) is # to be found. # TypesConfig /etc/mime.types # # DefaultType is the default MIME type the server will use for a document # if it cannot otherwise determine one, such as from filename extensions. # If your server contains mostly text or HTML documents, "text/plain" is # a good value. If most of your content is binary, such as applications # or images, you may want to use "application/octet-stream" instead to # keep browsers from trying to display binary files as though they are # text. # DefaultType text/plain # # The mod_mime_magic module allows the server to use various hints from the # contents of the file itself to determine its type. The MIMEMagicFile # directive tells the module where the hint definitions are located. # <IfModule mod_mime_magic.c> # MIMEMagicFile /usr/share/magic.mime MIMEMagicFile conf/magic </IfModule> # # HostnameLookups: Log the names of clients or just their IP addresses # e.g., www.apache.org (on) or 204.62.129.132 (off). # The default is off because it'd be overall better for the net if people # had to knowingly turn this feature on, since enabling it means that # each client request will result in AT LEAST one lookup request to the # nameserver. # HostnameLookups Off # # EnableMMAP: Control whether memory-mapping is used to deliver # files (assuming that the underlying OS supports it). # The default is on; turn this off if you serve from NFS-mounted # filesystems. On some systems, turning it off (regardless of # filesystem) can improve performance; for details, please see # http://httpd.apache.org/docs/2.2/mod/core.html#enablemmap # #EnableMMAP off # # EnableSendfile: Control whether the sendfile kernel support is # used to deliver files (assuming that the OS supports it). # The default is on; turn this off if you serve from NFS-mounted # filesystems. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#enablesendfile # #EnableSendfile off # # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog logs/error_log # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent # "combinedio" includes actual counts of actual bytes received (%I) and sent (%O); this # requires the mod_logio module to be loaded. #LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio # # The location and format of the access logfile (Common Logfile Format). # If you do not define any access logfiles within a <VirtualHost> # container, they will be logged here. Contrariwise, if you *do* # define per-<VirtualHost> access logfiles, transactions will be # logged therein and *not* in this file. # #CustomLog logs/access_log common # # If you would like to have separate agent and referer logfiles, uncomment # the following directives. # #CustomLog logs/referer_log referer #CustomLog logs/agent_log agent # # For a single logfile with access, agent, and referer information # (Combined Logfile Format), use the following directive: # CustomLog logs/access_log combined # # Optionally add a line containing the server version and virtual host # name to server-generated pages (internal error documents, FTP directory # listings, mod_status and mod_info output etc., but not CGI generated # documents or custom error documents). # Set to "EMail" to also include a mailto: link to the ServerAdmin. # Set to one of: On | Off | EMail # ServerSignature On # # Aliases: Add here as many aliases as you need (with no limit). The format is # Alias fakename realname # # Note that if you include a trailing / on fakename then the server will # require it to be present in the URL. So "/icons" isn't aliased in this # example, only "/icons/". If the fakename is slash-terminated, then the # realname must also be slash terminated, and if the fakename omits the # trailing slash, the realname must also omit it. # # We include the /icons/ alias for FancyIndexed directory listings. If you # do not use FancyIndexing, you may comment this out. # Alias /icons/ "/var/www/icons/" <Directory "/var/www/icons"> Options Indexes MultiViews AllowOverride None Order allow,deny Allow from all </Directory> # # WebDAV module configuration section. # <IfModule mod_dav_fs.c> # Location of the WebDAV lock database. DAVLockDB /var/lib/dav/lockdb </IfModule> # # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the realname directory are treated as applications and # run by the server when requested rather than as documents sent to the client. # The same rules about trailing "/" apply to ScriptAlias directives as to # Alias. # ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" # # "/var/www/cgi-bin" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # <Directory "/var/www/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all </Directory> # # Redirect allows you to tell clients about documents which used to exist in # your server's namespace, but do not anymore. This allows you to tell the # clients where to look for the relocated document. # Example: # Redirect permanent /foo http://www.example.com/bar # # Directives controlling the display of server-generated directory listings. # # # IndexOptions: Controls the appearance of server-generated directory # listings. # IndexOptions FancyIndexing VersionSort NameWidth=* HTMLTable # # AddIcon* directives tell the server which icon to show for different # files or filename extensions. These are only displayed for # FancyIndexed directories. # AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip AddIconByType (TXT,/icons/text.gif) text/* AddIconByType (IMG,/icons/image2.gif) image/* AddIconByType (SND,/icons/sound2.gif) audio/* AddIconByType (VID,/icons/movie.gif) video/* AddIcon /icons/binary.gif .bin .exe AddIcon /icons/binhex.gif .hqx AddIcon /icons/tar.gif .tar AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip AddIcon /icons/a.gif .ps .ai .eps AddIcon /icons/layout.gif .html .shtml .htm .pdf AddIcon /icons/text.gif .txt AddIcon /icons/c.gif .c AddIcon /icons/p.gif .pl .py AddIcon /icons/f.gif .for AddIcon /icons/dvi.gif .dvi AddIcon /icons/uuencoded.gif .uu AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl AddIcon /icons/tex.gif .tex AddIcon /icons/bomb.gif core AddIcon /icons/back.gif .. AddIcon /icons/hand.right.gif README AddIcon /icons/folder.gif ^^DIRECTORY^^ AddIcon /icons/blank.gif ^^BLANKICON^^ # # DefaultIcon is which icon to show for files which do not have an icon # explicitly set. # DefaultIcon /icons/unknown.gif # # AddDescription allows you to place a short description after a file in # server-generated indexes. These are only displayed for FancyIndexed # directories. # Format: AddDescription "description" filename # #AddDescription "GZIP compressed document" .gz #AddDescription "tar archive" .tar #AddDescription "GZIP compressed tar archive" .tgz # # ReadmeName is the name of the README file the server will look for by # default, and append to directory listings. # # HeaderName is the name of a file which should be prepended to # directory indexes. ReadmeName README.html HeaderName HEADER.html # # IndexIgnore is a set of filenames which directory indexing should ignore # and not include in the listing. Shell-style wildcarding is permitted. # IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t # # DefaultLanguage and AddLanguage allows you to specify the language of # a document. You can then use content negotiation to give a browser a # file in a language the user can understand. # # Specify a default language. This means that all data # going out without a specific language tag (see below) will # be marked with this one. You probably do NOT want to set # this unless you are sure it is correct for all cases. # # * It is generally better to not mark a page as # * being a certain language than marking it with the wrong # * language! # # DefaultLanguage nl # # Note 1: The suffix does not have to be the same as the language # keyword --- those with documents in Polish (whose net-standard # language code is pl) may wish to use "AddLanguage pl .po" to # avoid the ambiguity with the common suffix for perl scripts. # # Note 2: The example entries below illustrate that in some cases # the two character 'Language' abbreviation is not identical to # the two character 'Country' code for its country, # E.g. 'Danmark/dk' versus 'Danish/da'. # # Note 3: In the case of 'ltz' we violate the RFC by using a three char # specifier. There is 'work in progress' to fix this and get # the reference data for rfc1766 cleaned up. # # Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) # English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) # Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) # Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) # Norwegian (no) - Polish (pl) - Portugese (pt) # Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) # Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) # AddLanguage ca .ca AddLanguage cs .cz .cs AddLanguage da .dk AddLanguage de .de AddLanguage el .el AddLanguage en .en AddLanguage eo .eo AddLanguage es .es AddLanguage et .et AddLanguage fr .fr AddLanguage he .he AddLanguage hr .hr AddLanguage it .it AddLanguage ja .ja AddLanguage ko .ko AddLanguage ltz .ltz AddLanguage nl .nl AddLanguage nn .nn AddLanguage no .no AddLanguage pl .po AddLanguage pt .pt AddLanguage pt-BR .pt-br AddLanguage ru .ru AddLanguage sv .sv AddLanguage zh-CN .zh-cn AddLanguage zh-TW .zh-tw # # LanguagePriority allows you to give precedence to some languages # in case of a tie during content negotiation. # # Just list the languages in decreasing order of preference. We have # more or less alphabetized them here. You probably want to change this. # LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW # # ForceLanguagePriority allows you to serve a result page rather than # MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) # [in case no accepted languages matched the available variants] # ForceLanguagePriority Prefer Fallback # # Specify a default charset for all content served; this enables # interpretation of all content as UTF-8 by default. To use the # default browser choice (ISO-8859-1), or to allow the META tags # in HTML content to override this choice, comment out this # directive: # AddDefaultCharset UTF-8 # # AddType allows you to add to or override the MIME configuration # file mime.types for specific file types. # #AddType application/x-tar .tgz # # AddEncoding allows you to have certain browsers uncompress # information on the fly. Note: Not all browsers support this. # Despite the name similarity, the following Add* directives have nothing # to do with the FancyIndexing customization directives above. # #AddEncoding x-compress .Z #AddEncoding x-gzip .gz .tgz # If the AddEncoding directives above are commented-out, then you # probably should define those extensions to indicate media types: # AddType application/x-compress .Z AddType application/x-gzip .gz .tgz # # AddHandler allows you to map certain file extensions to "handlers": # actions unrelated to filetype. These can be either built into the server # or added with the Action directive (see below) # # To use CGI scripts outside of ScriptAliased directories: # (You will also need to add "ExecCGI" to the "Options" directive.) # #AddHandler cgi-script .cgi # # For files that include their own HTTP headers: # #AddHandler send-as-is asis # # For type maps (negotiated resources): # (This is enabled by default to allow the Apache "It Worked" page # to be distributed in multiple languages.) # AddHandler type-map var # # Filters allow you to process content before it is sent to the client. # # To parse .shtml files for server-side includes (SSI): # (You will also need to add "Includes" to the "Options" directive.) # AddType text/html .shtml AddOutputFilter INCLUDES .shtml # # Action lets you define media types that will execute a script whenever # a matching file is called. This eliminates the need for repeated URL # pathnames for oft-used CGI file processors. # Format: Action media/type /cgi-script/location # Format: Action handler-name /cgi-script/location # # # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: #ErrorDocument 500 "The server made a boo boo." #ErrorDocument 404 /missing.html #ErrorDocument 404 "/cgi-bin/missing_handler.pl" #ErrorDocument 402 http://www.example.com/subscription_info.html # # # Putting this all together, we can internationalize error responses. # # We use Alias to redirect any /error/HTTP_<error>.html.var response to # our collection of by-error message multi-language collections. We use # includes to substitute the appropriate text. # # You can modify the messages' appearance without changing any of the # default HTTP_<error>.html.var files by adding the line: # # Alias /error/include/ "/your/include/path/" # # which allows you to create your own set of files by starting with the # /var/www/error/include/ files and # copying them to /your/include/path/, even on a per-VirtualHost basis. # Alias /error/ "/var/www/error/" <IfModule mod_negotiation.c> <IfModule mod_include.c> <Directory "/var/www/error"> AllowOverride None Options IncludesNoExec AddOutputFilter Includes html AddHandler type-map var Order allow,deny Allow from all LanguagePriority en es de fr ForceLanguagePriority Prefer Fallback </Directory> # ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var # ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var # ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var # ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var # ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var # ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var # ErrorDocument 410 /error/HTTP_GONE.html.var # ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var # ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var # ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var # ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var # ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var # ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var # ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var # ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var # ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var # ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var </IfModule> </IfModule> # # The following directives modify normal HTTP response behavior to # handle known problems with browser implementations. # BrowserMatch "Mozilla/2" nokeepalive BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 BrowserMatch "RealPlayer 4\.0" force-response-1.0 BrowserMatch "Java/1\.0" force-response-1.0 BrowserMatch "JDK/1\.0" force-response-1.0 # # The following directive disables redirects on non-GET requests for # a directory that does not include the trailing slash. This fixes a # problem with Microsoft WebFolders which does not appropriately handle # redirects for folders with DAV methods. # Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. # BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully BrowserMatch "MS FrontPage" redirect-carefully BrowserMatch "^WebDrive" redirect-carefully BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully BrowserMatch "^gnome-vfs/1.0" redirect-carefully BrowserMatch "^XML Spy" redirect-carefully BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully # # Allow server status reports generated by mod_status, # with the URL of http://servername/server-status # Change the ".example.com" to match your domain to enable. # #<Location /server-status> # SetHandler server-status # Order deny,allow # Deny from all # Allow from .example.com #</Location> # # Allow remote server configuration reports, with the URL of # http://servername/server-info (requires that mod_info.c be loaded). # Change the ".example.com" to match your domain to enable. # #<Location /server-info> # SetHandler server-info # Order deny,allow # Deny from all # Allow from .example.com #</Location> # # Proxy Server directives. Uncomment the following lines to # enable the proxy server: # #<IfModule mod_proxy.c> #ProxyRequests On # #<Proxy *> # Order deny,allow # Deny from all # Allow from .example.com #</Proxy> # # Enable/disable the handling of HTTP/1.1 "Via:" headers. # ("Full" adds the server version; "Block" removes all outgoing Via: headers) # Set to one of: Off | On | Full | Block # #ProxyVia On # # To enable a cache of proxied content, uncomment the following lines. # See http://httpd.apache.org/docs/2.2/mod/mod_cache.html for more details. # #<IfModule mod_disk_cache.c> # CacheEnable disk / # CacheRoot "/var/cache/mod_proxy" #</IfModule> # #</IfModule> # End of proxy directives. ### Section 3: Virtual Hosts # # VirtualHost: If you want to maintain multiple domains/hostnames on your # machine you can setup VirtualHost containers for them. Most configurations # use only name-based virtual hosts so the server doesn't need to worry about # IP addresses. This is indicated by the asterisks in the directives below. # # Please see the documentation at # <URL:http://httpd.apache.org/docs/2.2/vhosts/> # for further details before you try to setup virtual hosts. # # You may use the command line option '-S' to verify your virtual host # configuration. # # Use name-based virtual hosting. # #NameVirtualHost *:80 # # NOTE: NameVirtualHost cannot be used without a port specifier # (e.g. :80) if mod_ssl is being used, due to the nature of the # SSL protocol. # # # VirtualHost example: # Almost any Apache directive may go into a VirtualHost container. # The first VirtualHost section is used for requests without a known # server name. # #<VirtualHost *:80> # ServerAdmin webmaster@dummy-host.example.com # DocumentRoot /www/docs/dummy-host.example.com # ServerName dummy-host.example.com # ErrorLog logs/dummy-host.example.com-error_log # CustomLog logs/dummy-host.example.com-access_log common #</VirtualHost>
指定的参数已超出有效值的范围。 参数名: index?
asp.net初学者 出错代码旁边注释掉的是之前的写法。。不会改啊要抓狂了!!!!麻烦各界大神指正!还挺着急的。。悬赏我可以加,回答的时候贴上改正后的代码好不???? ``` <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="adminList.aspx.cs" Inherits="Last.Last" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>adminlist</title> <link rel="stylesheet" type="text/css" href="css/index.css"/> <link rel="stylesheet" type="text/css" href="css/adminList.css" /> </head> <body> <form id="form1" runat="server"> <!-- 管理员列表 --> <div id="admin_list"> <div class="header radius"> <h3>管理员列表</h3> </div> <div class="admin_list_content"> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound"> <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <Columns> <asp:TemplateField> <ItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="id" HeaderText="" ReadOnly="True" /> <%--只能读取 不能编辑改变值 这是搜寻的标杆--%> <asp:BoundField DataField="List" HeaderText="管理员列表" /> <asp:BoundField DataField="Name" HeaderText="管理员姓名" /> <asp:BoundField DataField="Type" HeaderText="管理员类型" /> <asp:BoundField DataField="Range" HeaderText="管理员区域" /> <asp:CommandField HeaderText="修改" ButtonType="image" EditImageUrl="./images/change.png" ShowEditButton="True" /> <asp:CommandField HeaderText="删除" ButtonType="image" EditImageUrl="./images/remove.png" ShowEditButton="True" /> </Columns> <RowStyle ForeColor="Black" /> <%--字体颜色--%> <PagerStyle BackColor="white" ForeColor="white" HorizontalAlign="Left" /> <HeaderStyle BackColor="White" Font-Bold="True" ForeColor="Black" /> <%--背景色 题头颜色 --%> </asp:GridView> <br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<asp:TextBox ID="Num" TextMode="SingleLine" runat="server" Height="30px" Width="30px"></asp:TextBox> <asp:TextBox ID="List" TextMode="SingleLine" runat="server" Height="30px" Width="230px"></asp:TextBox> <asp:TextBox ID="Name" TextMode="SingleLine" runat="server" Height="30px" Width="320px"></asp:TextBox> <asp:TextBox ID="Type" TextMode="SingleLine" runat="server" Height="30px" Width="225px"></asp:TextBox> <asp:TextBox ID="Range" TextMode="SingleLine" runat="server" Height="30px" Width="320px"></asp:TextBox> <asp:Button ID="AddAdmin" runat="server" OnClick="AddAdmin_Click" Text="添加管理员" Width="100px" Height="30px" /> </div> </div> </form> </body> </html> using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Last { public partial class Last : System.Web.UI.Page { SqlConnection sqlcon; SqlCommand sqlcom; string strCon = "server=.;database=ado;uid=sa;pwd=123456"; protected void Page_Load(object sender, EventArgs e) { //获取一个值,该值显示页上呈现第一次还是正在加载中发出的响应 if (!IsPostBack)//刷新后展现修改后的内容 { bind(); } } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex;//将文本框输入的内容传到gv代码里面,代码操控着数据库 bind(); } //删除 protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { string sqlstr = "delete from ado.dbo.ziliao where 管理员列表='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";//获取要删除的id sqlcon = new SqlConnection(strCon); sqlcom = new SqlCommand(sqlstr, sqlcon);//命令删除语句 sqlcon.Open(); sqlcom.ExecuteNonQuery();//执行 sqlcon.Close(); bind(); } //更新 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { string sqlstr = "update ado.dbo.adminList set List='"+ ((TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0])).Text.ToString().Trim() + "',Name='"+ ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',Type='" + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "',Range='"+ GridView1.Rows[e.RowIndex].Cells[3].Controls[0].ToString().Trim() + "' where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'"; SqlHelper.ExecuteNonQuery(sqlstr); sqlcon.Close(); GridView1.EditIndex = -1;//退出当前编辑状态(GridView1是从第0行开始编辑),切换到浏览模式 bind(); } //取消 protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1;//退出当前编辑状态(GridView1是从第0行开始编辑),切换到浏览模式 bind(); } //绑定 public void bind() { string sqlstr = "select * from ado.dbo.adminList"; sqlcon = new SqlConnection(strCon); SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon); DataSet myds = new DataSet(); sqlcon.Open(); myda.Fill(myds, "ado.dbo.adminList"); GridView1.DataSource = myds;//将GridView的数据库绑定到指定数据库 GridView1.DataBind(); sqlcon.Close(); } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //首先判断是否是数据行 if (e.Row.RowType == DataControlRowType.DataRow) { //当鼠标停留时更改背景色 e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#d7d7f1'"); //当鼠标移开时还原背景色 e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c"); } //if (e.Row.RowType == DataControlRowType.DataRow) //{ // e.Row.Cells[6].Text = " <img src='Images/change.png' style='width: 20;height: 20;'/>" + e.Row.Cells[1].Text; // e.Row.Cells[7].Text = " <img src='Images/remove.png' style='width: 20;height: 20;'/>" + e.Row.Cells[1].Text; //} } SqlConnection con = new SqlConnection("server=.;database=ado;uid=sa;pwd=123456");//创建连接对象 protected void AddAdmin_Click(object sender, EventArgs e) { string Sql = "select * from ado.dbo.adminList where List='" + List.Text + "'"; SqlDataAdapter da = new SqlDataAdapter(Sql, con); //创建适配器 DataSet ds = new DataSet(); //创建数据集 da.Fill(ds, "table"); //填充数据集 if (da.Fill(ds, "table") > 0) //同用户名 { Response.Write("<script>alert('新增失败,存在相同用户名')</script>");//输出信息 } else//不同用户名 { string text5 = Num.Text.Trim(); string text1 = List.Text.Trim(); string text2 = Name.Text.Trim(); string text3 = Type.Text.Trim(); string text4 = Range.Text.Trim(); string str = "insert into ado.dbo.adminList (id,List,Name,Type,Range) VALUES('" + text5 + "','" + text1 + "','" + text2 + "','" + text3 + "','" + text4 + "')"; if (SqlHelper.ExecuteNonQuery(str) > 0)//执行成功 { Response.Redirect(Request.Url.ToString()); } else//执行失败 { Response.Write("<script>alert('增加失败,请检查系统内部')</script>");//输出信息 } } } } } ``` ![图片说明](https://img-ask.csdn.net/upload/201908/09/1565337412_110449.png) ![图片说明](https://img-ask.csdn.net/upload/201908/09/1565338046_314223.png) ![图片说明](https://img-ask.csdn.net/upload/201908/09/1565338057_516946.png)
Nginx 关于不安全字符转义如何处理?
使用Nginx进行反向代理,在分发请求发现,不安全字符在nginx里没有被转义,秋解决办法 配置如下 ``` worker_processes 2; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log logs/access.log main; rewrite_log on; sendfile on; keepalive_timeout 65; server { listen 99; server_name server8.example.com; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 1024m; client_header_buffer_size 16m; large_client_header_buffers 4 64m; location / { proxy_pass http://127.0.0.1:8080/; #set $kas "%7C"; 这样强制赋值成转义编码,但是转发出去的时候被还原成| #rewrite ^/http://(.*)[|](.*)[|](.*) http://$1$kas$2$kas$3 break; proxy_connect_timeout 600; proxy_read_timeout 600; } } } ```
php怎么调用wcf服务,调用参数是对象参数。
.net做的wcf接口,部署IIS上访问是可以的如图: ![](http://e.hiphotos.baidu.com/zhidao/wh%3D600%2C800/sign=327a4d70a96eddc426b2bcfd09eb9ac5/8d5494eef01f3a29117bb65b9d25bc315d607cf7.jpg) 我用php soap调用测试,是否能通,也是可以的: <?php header('Content-Type: text/plain'); $client = new SoapClient('http://testu.sh.jinri.com/Flight.User.SOA/SuggestService.svc?wsdl'); echo '<xmp>'; echo "提供的方法\n"; print_r( $client->__getFunctions ()); echo "相关的数据结构\n"; print_r($client->__getTypes () ); echo '</xmp>'; ?> 浏览器上看到的结果如图: ![](http://c.hiphotos.baidu.com/zhidao/pic/item/6d81800a19d8bc3ee3a5645f868ba61ea9d345f1.jpg) 调用wcf中的这个方法:GetSuggestList 这个方法在接口里面是这样的: public GetSuggestListResponse GetSuggestList(GetSuggestListRequest request) 所以参数是个对象 我用PHP调用如下: $client = new SoapClient('http://testu.sh.jinri.com/Flight.User.SOA/SuggestService.svc?wsdl'); $param = array('UserId'=>'1920','PageIndex'=>'1','PageSize'=>'5'); print_r($client->GetSuggestList($param)); 但是抛出这样的的错误: Fatal error: Uncaught SoapFault exception: [a:InternalServiceFault] 未将对象引用设置到对象的实例。 in D:\APMServ5.2.6\www\htdocs\wsdltest\index.php:22 Stack trace: #0 [internal function]: SoapClient->__call('GetSuggestList', Array) #1 D:\APMServ5.2.6\www\htdocs\wsdltest\index.php(22): SoapClient->GetSuggestList(Array) #2 {main} thrown inD:\APMServ5.2.6\www\htdocs\wsdltest\index.php on line 22 求大神帮忙,整了一天了,不知道啥原因。
oa上传文件不能超过1M
从11月1日起,以域名在处于公网的办公电脑、oa服务器上通过ie、猎豹浏览器、火狐浏览器登录oa,写邮件时添加大于1024k的附件并上传该附件时,或在个人文件夹上传在大于1024k的文件时,出现错误,提示:413 Request Entity Too Large --nginx/1.6.2。 在处于内网办公电脑上以oa服务器的内网地址的方式登录oa,则无上述问题。在oa服务器上通过localhost登录oa,也无上述问题。 打开nginx主配置文件nginx.conf,http段内容如下: http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; access_log off; server_tokens off; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 10; keepalive_requests 0; gzip on; gzip_comp_level 9; gzip_min_length 1k; gzip_buffers 4 16k; gzip_http_version 1.1; gzip_types text/plain application/x-javascript text/css text/xml; gzip_vary on; gzip_static on; gzip_proxied any; gzip_disable "MSIE [1-6]\."; #upstream myoa { # server localhost:81 weight=1; # server localhost:82 weight=1; # keepalive 100; #} server { #Nginx端口 listen 81; server_name localhost; root C:/MYOA/webroot/; index index.php index.html index.htm; include common.conf; #charset gbk; #access_log logs/host.access.log main; #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # location ~* (\.php$|/general/itask/|/general/document/) { #Apache地址和端口 proxy_pass http://localhost:80; include proxy.conf; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } 打开proxy.conf,内容如下: proxy_http_version 1.1; proxy_set_header Connection ""; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $http_host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_buffering off; proxy_buffer_size 8k; proxy_buffers 4 8k; client_max_body_size 200m; client_body_buffer_size 256k; proxy_connect_timeout 60; proxy_send_timeout 1200; proxy_read_timeout 1200; proxy_next_upstream error timeout invalid_header http_500 http_503 http_404; proxy_max_temp_file_size 128m;
用Nginx实现均衡负载效率反而降低,为什么?
我在Win7系统下安装了两个tomcat,一个8080端口,一个8088端口。跑着同样的WEB项目。然后在Win7下用VMWare装了个CentOS6.5虚拟机,在该虚拟机上安装并配置了Nginx。然后在该虚拟机上用apache ab进行压力测试,结果用nginx反而比不用差一些。请高手帮助解惑!!! 下面是我的测试方法和结果: [root@localhost local]# ab -n 10000 -c 1000 -H "Authorization: Digest username="cpe", realm="SWACS", nonce="2ef7d7f74e136a548362a488fa1ca753",uri="/SWTMS/acs", qop="auth", nc=00000001, cnonce="1243442698", response="78374f1538516f6055faf0dcab6571a7",opaque="A0720F8F9F1C4EC1B108C201E4660C79"" -p ./inform.txt http://172.16.15.110:8080/SWTMS/acs(这是直接访问tomcat,访问nginx则是把url改成http://172.16.15.111/SWTMS/acs) This is ApacheBench, Version 2.3 <$Revision: 655654 $> Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking 172.16.15.110 (be patient) Completed 1000 requests Completed 2000 requests Completed 3000 requests Completed 4000 requests Completed 5000 requests Completed 6000 requests Completed 7000 requests Completed 8000 requests Completed 9000 requests Completed 10000 requests Finished 10000 requests Server Software: Apache-Coyote/1.1 Server Hostname: 172.16.15.110 Server Port: 8080 Document Path: /SWTMS/acs Document Length: 549 bytes Concurrency Level: 1000 Time taken for tests: 10.269 seconds Complete requests: 10000 Failed requests: 0 Write errors: 0 Total transferred: 7910000 bytes Total POSTed: 32570000 HTML transferred: 5490000 bytes Requests per second: 973.81 [#/sec] (mean) Time per request: 1026.895 [ms] (mean) Time per request: 1.027 [ms] (mean, across all concurrent requests) 下面是我的Nginx配置: #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; error_log logs/error.log info; pid logs/nginx.pid; worker_rlimit_nofile 65535; events { worker_connections 65535; multi_accept on; use epoll; } http { include mime.types; default_type application/octet-stream; charset utf-8; #默认编码 server_names_hash_bucket_size 128; #服务器名字的hash表大小 client_header_buffer_size 32k; #上传文件大小限制 large_client_header_buffers 4 64k; #设定请求缓 client_max_body_size 8m; #设定请求缓 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log logs/access.log main; sendfile on; tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; tcp_nodelay on; #FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。 fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; fastcgi_buffer_size 64k; fastcgi_buffers 4 64k; fastcgi_busy_buffers_size 128k; fastcgi_temp_file_write_size 128k; #gzip模块设置 gzip on; #开启gzip压缩输出 gzip_min_length 1k; #最小压缩文件大小 gzip_buffers 4 16k; #压缩缓冲区 gzip_http_version 1.1; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0) gzip_comp_level 2; #压缩等级 gzip_types text/plain application/x-javascript text/css application/xml; #压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。 gzip_vary on; upstream tomcats { server 172.16.15.110:8088 weight=1; server 172.16.15.110:8080 weight=1; #ip_hash; } server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; proxy_pass http://tomcats; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 50m; client_body_buffer_size 256k; proxy_connect_timeout 10; proxy_send_timeout 15; proxy_read_timeout 15; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #} }
小白使用keil编程debug进入了harddefault,搞了半天没解决。求大佬帮下忙。
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "can.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ void CAN_SetTxMsg(void) { hcan.pTxMsg->ExtId=0x1314; //使用的扩展ID hcan.pTxMsg->IDE=CAN_ID_EXT; //扩展模式 hcan.pTxMsg->RTR=CAN_RTR_DATA; //发送的是数据 hcan.pTxMsg->DLC=8; //数据长度为2字节 hcan.pTxMsg->data[0]=0x01; hcan.pTxMsg->data[1]=0x02; hcan.pTxMsg->data[2]=0x03; hcan.pTxMsg->data[3]=0x04; hcan.pTxMsg->data[4]=0x05; hcan.pTxMsg->data[5]=0x06; hcan.pTxMsg->data[6]=0x07; hcan.pTxMsg->data[7]=0x08; } /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_CAN_Init(); MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ CAN_SetTxMsg(); HAL_CAN_AddTxMessage(&hcan,hcan.pTxMsg,hcan.pTxMsg->data,(uint32_t*)CAN_TX_MAILBOX0); HAL_CAN_ActivateNotification(&hcan,CAN_IT_RX_FIFO0_MSG_PENDING); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; /** Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } /** Enables the Clock Security System */ HAL_RCC_EnableCSS(); } /* USER CODE BEGIN 4 */ void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) { HAL_CAN_AddTxMessage(hcan,hcan->pTxMsg,hcan->pTxMsg->data,(uint32_t*)CAN_TX_MAILBOX0); HAL_CAN_ActivateNotification(hcan,CAN_IT_RX_FIFO0_MSG_PENDING); } /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ 这是我的主程序,debug总是在CAN_SetMsg()那里进入了hardfault.下面是定义的一些初始化结构体。 /** ****************************************************************************** * @file stm32f1xx_hal_can.h * @author MCD Application Team * @brief Header file of CAN HAL module. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32F1xx_HAL_CAN_H #define STM32F1xx_HAL_CAN_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32f1xx_hal_def.h" /** @addtogroup STM32F1xx_HAL_Driver * @{ */ #if defined (CAN1) /** @addtogroup CAN * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup CAN_Exported_Types CAN Exported Types * @{ */ /** * @brief HAL State structures definition */ typedef enum { HAL_CAN_STATE_RESET = 0x00U, /*!< CAN not yet initialized or disabled */ HAL_CAN_STATE_READY = 0x01U, /*!< CAN initialized and ready for use */ HAL_CAN_STATE_LISTENING = 0x02U, /*!< CAN receive process is ongoing */ HAL_CAN_STATE_SLEEP_PENDING = 0x03U, /*!< CAN sleep request is pending */ HAL_CAN_STATE_SLEEP_ACTIVE = 0x04U, /*!< CAN sleep mode is active */ HAL_CAN_STATE_ERROR = 0x05U /*!< CAN error state */ } HAL_CAN_StateTypeDef; /** * @brief CAN init structure definition */ typedef struct { uint32_t Prescaler; /*!< Specifies the length of a time quantum. This parameter must be a number between Min_Data = 1 and Max_Data = 1024. */ uint32_t Mode; /*!< Specifies the CAN operating mode. This parameter can be a value of @ref CAN_operating_mode */ uint32_t SyncJumpWidth; /*!< Specifies the maximum number of time quanta the CAN hardware is allowed to lengthen or shorten a bit to perform resynchronization. This parameter can be a value of @ref CAN_synchronisation_jump_width */ uint32_t TimeSeg1; /*!< Specifies the number of time quanta in Bit Segment 1. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_1 */ uint32_t TimeSeg2; /*!< Specifies the number of time quanta in Bit Segment 2. This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_2 */ FunctionalState TimeTriggeredMode; /*!< Enable or disable the time triggered communication mode. This parameter can be set to ENABLE or DISABLE. */ FunctionalState AutoBusOff; /*!< Enable or disable the automatic bus-off management. This parameter can be set to ENABLE or DISABLE. */ FunctionalState AutoWakeUp; /*!< Enable or disable the automatic wake-up mode. This parameter can be set to ENABLE or DISABLE. */ FunctionalState AutoRetransmission; /*!< Enable or disable the non-automatic retransmission mode. This parameter can be set to ENABLE or DISABLE. */ FunctionalState ReceiveFifoLocked; /*!< Enable or disable the Receive FIFO Locked mode. This parameter can be set to ENABLE or DISABLE. */ FunctionalState TransmitFifoPriority;/*!< Enable or disable the transmit FIFO priority. This parameter can be set to ENABLE or DISABLE. */ } CAN_InitTypeDef; /** * @brief CAN filter configuration structure definition */ typedef struct { uint32_t FilterIdHigh; /*!< Specifies the filter identification number (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t FilterIdLow; /*!< Specifies the filter identification number (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t FilterMaskIdHigh; /*!< Specifies the filter mask number or identification number, according to the mode (MSBs for a 32-bit configuration, first one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t FilterMaskIdLow; /*!< Specifies the filter mask number or identification number, according to the mode (LSBs for a 32-bit configuration, second one for a 16-bit configuration). This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ uint32_t FilterFIFOAssignment; /*!< Specifies the FIFO (0 or 1U) which will be assigned to the filter. This parameter can be a value of @ref CAN_filter_FIFO */ uint32_t FilterBank; /*!< Specifies the filter bank which will be initialized. For single CAN instance(14 dedicated filter banks), this parameter must be a number between Min_Data = 0 and Max_Data = 13. For dual CAN instances(28 filter banks shared), this parameter must be a number between Min_Data = 0 and Max_Data = 27. */ uint32_t FilterMode; /*!< Specifies the filter mode to be initialized. This parameter can be a value of @ref CAN_filter_mode */ uint32_t FilterScale; /*!< Specifies the filter scale. This parameter can be a value of @ref CAN_filter_scale */ uint32_t FilterActivation; /*!< Enable or disable the filter. This parameter can be a value of @ref CAN_filter_activation */ uint32_t SlaveStartFilterBank; /*!< Select the start filter bank for the slave CAN instance. For single CAN instances, this parameter is meaningless. For dual CAN instances, all filter banks with lower index are assigned to master CAN instance, whereas all filter banks with greater index are assigned to slave CAN instance. This parameter must be a number between Min_Data = 0 and Max_Data = 27. */ } CAN_FilterTypeDef; /** * @brief CAN Tx message header structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. This parameter can be a value of @ref CAN_identifier_type */ uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ uint8_t data[8]; FunctionalState TransmitGlobalTime; /*!< Specifies whether the timestamp counter value captured on start of frame transmission, is sent in DATA6 and DATA7 replacing pData[6] and pData[7]. @note: Time Triggered Communication Mode must be enabled. @note: DLC must be programmed as 8 bytes, in order these 2 bytes are sent. This parameter can be set to ENABLE or DISABLE. */ } CAN_TxHeaderTypeDef; /** * @brief CAN Rx message header structure definition */ typedef struct { uint32_t StdId; /*!< Specifies the standard identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ uint32_t ExtId; /*!< Specifies the extended identifier. This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. This parameter can be a value of @ref CAN_identifier_type */ uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. This parameter can be a value of @ref CAN_remote_transmission_request */ uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ uint8_t Data[8]; uint32_t Timestamp; /*!< Specifies the timestamp counter value captured on start of frame reception. @note: Time Triggered Communication Mode must be enabled. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFFFF. */ uint32_t FilterMatchIndex; /*!< Specifies the index of matching acceptance filter element. This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ } CAN_RxHeaderTypeDef; /** * @brief CAN handle Structure definition */ typedef struct __CAN_HandleTypeDef { CAN_TypeDef *Instance; /*!< Register base address */ CAN_InitTypeDef Init; /*!< CAN required parameters */ CAN_TxHeaderTypeDef* pTxMsg; CAN_RxHeaderTypeDef* pRxMsg; HAL_LockTypeDef Lock; __IO HAL_CAN_StateTypeDef State; /*!< CAN communication state */ __IO uint32_t ErrorCode; /*!< CAN Error code. This parameter can be a value of @ref CAN_Error_Code */ } CAN_HandleTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ /** @defgroup CAN_Exported_Constants CAN Exported Constants * @{ */ /** @defgroup CAN_Error_Code CAN Error Code * @{ */ #define HAL_CAN_ERROR_NONE (0x00000000U) /*!< No error */ #define HAL_CAN_ERROR_EWG (0x00000001U) /*!< Protocol Error Warning */ #define HAL_CAN_ERROR_EPV (0x00000002U) /*!< Error Passive */ #define HAL_CAN_ERROR_BOF (0x00000004U) /*!< Bus-off error */ #define HAL_CAN_ERROR_STF (0x00000008U) /*!< Stuff error */ #define HAL_CAN_ERROR_FOR (0x00000010U) /*!< Form error */ #define HAL_CAN_ERROR_ACK (0x00000020U) /*!< Acknowledgment error */ #define HAL_CAN_ERROR_BR (0x00000040U) /*!< Bit recessive error */ #define HAL_CAN_ERROR_BD (0x00000080U) /*!< Bit dominant error */ #define HAL_CAN_ERROR_CRC (0x00000100U) /*!< CRC error */ #define HAL_CAN_ERROR_RX_FOV0 (0x00000200U) /*!< Rx FIFO0 overrun error */ #define HAL_CAN_ERROR_RX_FOV1 (0x00000400U) /*!< Rx FIFO1 overrun error */ #define HAL_CAN_ERROR_TX_ALST0 (0x00000800U) /*!< TxMailbox 0 transmit failure due to arbitration lost */ #define HAL_CAN_ERROR_TX_TERR0 (0x00001000U) /*!< TxMailbox 1 transmit failure due to tranmit error */ #define HAL_CAN_ERROR_TX_ALST1 (0x00002000U) /*!< TxMailbox 0 transmit failure due to arbitration lost */ #define HAL_CAN_ERROR_TX_TERR1 (0x00004000U) /*!< TxMailbox 1 transmit failure due to tranmit error */ #define HAL_CAN_ERROR_TX_ALST2 (0x00008000U) /*!< TxMailbox 0 transmit failure due to arbitration lost */ #define HAL_CAN_ERROR_TX_TERR2 (0x00010000U) /*!< TxMailbox 1 transmit failure due to tranmit error */ #define HAL_CAN_ERROR_TIMEOUT (0x00020000U) /*!< Timeout error */ #define HAL_CAN_ERROR_NOT_INITIALIZED (0x00040000U) /*!< Peripheral not initialized */ #define HAL_CAN_ERROR_NOT_READY (0x00080000U) /*!< Peripheral not ready */ #define HAL_CAN_ERROR_NOT_STARTED (0x00100000U) /*!< Peripheral not started */ #define HAL_CAN_ERROR_PARAM (0x00200000U) /*!< Parameter error */ #define HAL_CAN_ERROR_INTERNAL (0x00800000U) /*!< Internal error */ /** * @} */ /** @defgroup CAN_InitStatus CAN InitStatus * @{ */ #define CAN_INITSTATUS_FAILED (0x00000000U) /*!< CAN initialization failed */ #define CAN_INITSTATUS_SUCCESS (0x00000001U) /*!< CAN initialization OK */ /** * @} */ /** @defgroup CAN_operating_mode CAN Operating Mode * @{ */ #define CAN_MODE_NORMAL (0x00000000U) /*!< Normal mode */ #define CAN_MODE_LOOPBACK ((uint32_t)CAN_BTR_LBKM) /*!< Loopback mode */ #define CAN_MODE_SILENT ((uint32_t)CAN_BTR_SILM) /*!< Silent mode */ #define CAN_MODE_SILENT_LOOPBACK ((uint32_t)(CAN_BTR_LBKM | CAN_BTR_SILM)) /*!< Loopback combined with silent mode */ /** * @} */ /** @defgroup CAN_synchronisation_jump_width CAN Synchronization Jump Width * @{ */ #define CAN_SJW_1TQ (0x00000000U) /*!< 1 time quantum */ #define CAN_SJW_2TQ ((uint32_t)CAN_BTR_SJW_0) /*!< 2 time quantum */ #define CAN_SJW_3TQ ((uint32_t)CAN_BTR_SJW_1) /*!< 3 time quantum */ #define CAN_SJW_4TQ ((uint32_t)CAN_BTR_SJW) /*!< 4 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_1 CAN Time Quantum in Bit Segment 1 * @{ */ #define CAN_BS1_1TQ (0x00000000U) /*!< 1 time quantum */ #define CAN_BS1_2TQ ((uint32_t)CAN_BTR_TS1_0) /*!< 2 time quantum */ #define CAN_BS1_3TQ ((uint32_t)CAN_BTR_TS1_1) /*!< 3 time quantum */ #define CAN_BS1_4TQ ((uint32_t)(CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 4 time quantum */ #define CAN_BS1_5TQ ((uint32_t)CAN_BTR_TS1_2) /*!< 5 time quantum */ #define CAN_BS1_6TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 6 time quantum */ #define CAN_BS1_7TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 7 time quantum */ #define CAN_BS1_8TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 8 time quantum */ #define CAN_BS1_9TQ ((uint32_t)CAN_BTR_TS1_3) /*!< 9 time quantum */ #define CAN_BS1_10TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_0)) /*!< 10 time quantum */ #define CAN_BS1_11TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1)) /*!< 11 time quantum */ #define CAN_BS1_12TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 12 time quantum */ #define CAN_BS1_13TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2)) /*!< 13 time quantum */ #define CAN_BS1_14TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 14 time quantum */ #define CAN_BS1_15TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 15 time quantum */ #define CAN_BS1_16TQ ((uint32_t)CAN_BTR_TS1) /*!< 16 time quantum */ /** * @} */ /** @defgroup CAN_time_quantum_in_bit_segment_2 CAN Time Quantum in Bit Segment 2 * @{ */ #define CAN_BS2_1TQ (0x00000000U) /*!< 1 time quantum */ #define CAN_BS2_2TQ ((uint32_t)CAN_BTR_TS2_0) /*!< 2 time quantum */ #define CAN_BS2_3TQ ((uint32_t)CAN_BTR_TS2_1) /*!< 3 time quantum */ #define CAN_BS2_4TQ ((uint32_t)(CAN_BTR_TS2_1 | CAN_BTR_TS2_0)) /*!< 4 time quantum */ #define CAN_BS2_5TQ ((uint32_t)CAN_BTR_TS2_2) /*!< 5 time quantum */ #define CAN_BS2_6TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_0)) /*!< 6 time quantum */ #define CAN_BS2_7TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_1)) /*!< 7 time quantum */ #define CAN_BS2_8TQ ((uint32_t)CAN_BTR_TS2) /*!< 8 time quantum */ /** * @} */ /** @defgroup CAN_filter_mode CAN Filter Mode * @{ */ #define CAN_FILTERMODE_IDMASK (0x00000000U) /*!< Identifier mask mode */ #define CAN_FILTERMODE_IDLIST (0x00000001U) /*!< Identifier list mode */ /** * @} */ /** @defgroup CAN_filter_scale CAN Filter Scale * @{ */ #define CAN_FILTERSCALE_16BIT (0x00000000U) /*!< Two 16-bit filters */ #define CAN_FILTERSCALE_32BIT (0x00000001U) /*!< One 32-bit filter */ /** * @} */ /** @defgroup CAN_filter_activation CAN Filter Activation * @{ */ #define CAN_FILTER_DISABLE (0x00000000U) /*!< Disable filter */ #define CAN_FILTER_ENABLE (0x00000001U) /*!< Enable filter */ /** * @} */ /** @defgroup CAN_filter_FIFO CAN Filter FIFO * @{ */ #define CAN_FILTER_FIFO0 (0x00000000U) /*!< Filter FIFO 0 assignment for filter x */ #define CAN_FILTER_FIFO1 (0x00000001U) /*!< Filter FIFO 1 assignment for filter x */ /** * @} */ /** @defgroup CAN_identifier_type CAN Identifier Type * @{ */ #define CAN_ID_STD ((uint32_t)0x00000000) /*!< Standard Id */ #define CAN_ID_EXT ((uint32_t)0x00000004) /*!< Extended Id */ /** * @} */ /** @defgroup CAN_remote_transmission_request CAN Remote Transmission Request * @{ */ #define CAN_RTR_DATA ((uint32_t)0x00000000) /*!< Data frame */ #define CAN_RTR_REMOTE ((uint32_t)0x00000002) /*!< Remote frame */ /** * @} */ /** @defgroup CAN_receive_FIFO_number CAN Receive FIFO Number * @{ */ #define CAN_RX_FIFO0 (0x00000000U) /*!< CAN receive FIFO 0 */ #define CAN_RX_FIFO1 (0x00000001U) /*!< CAN receive FIFO 1 */ /** * @} */ /** @defgroup CAN_Tx_Mailboxes CAN Tx Mailboxes * @{ */ #define CAN_TX_MAILBOX0 (0x00000001U) /*!< Tx Mailbox 0 */ #define CAN_TX_MAILBOX1 (0x00000002U) /*!< Tx Mailbox 1 */ #define CAN_TX_MAILBOX2 (0x00000004U) /*!< Tx Mailbox 2 */ /** * @} */ /** @defgroup CAN_flags CAN Flags * @{ */ /* Transmit Flags */ #define CAN_FLAG_RQCP0 (0x00000500U) /*!< Request complete MailBox 0 flag */ #define CAN_FLAG_TXOK0 (0x00000501U) /*!< Transmission OK MailBox 0 flag */ #define CAN_FLAG_ALST0 (0x00000502U) /*!< Arbitration Lost MailBox 0 flag */ #define CAN_FLAG_TERR0 (0x00000503U) /*!< Transmission error MailBox 0 flag */ #define CAN_FLAG_RQCP1 (0x00000508U) /*!< Request complete MailBox1 flag */ #define CAN_FLAG_TXOK1 (0x00000509U) /*!< Transmission OK MailBox 1 flag */ #define CAN_FLAG_ALST1 (0x0000050AU) /*!< Arbitration Lost MailBox 1 flag */ #define CAN_FLAG_TERR1 (0x0000050BU) /*!< Transmission error MailBox 1 flag */ #define CAN_FLAG_RQCP2 (0x00000510U) /*!< Request complete MailBox2 flag */ #define CAN_FLAG_TXOK2 (0x00000511U) /*!< Transmission OK MailBox 2 flag */ #define CAN_FLAG_ALST2 (0x00000512U) /*!< Arbitration Lost MailBox 2 flag */ #define CAN_FLAG_TERR2 (0x00000513U) /*!< Transmission error MailBox 2 flag */ #define CAN_FLAG_TME0 (0x0000051AU) /*!< Transmit mailbox 0 empty flag */ #define CAN_FLAG_TME1 (0x0000051BU) /*!< Transmit mailbox 1 empty flag */ #define CAN_FLAG_TME2 (0x0000051CU) /*!< Transmit mailbox 2 empty flag */ #define CAN_FLAG_LOW0 (0x0000051DU) /*!< Lowest priority mailbox 0 flag */ #define CAN_FLAG_LOW1 (0x0000051EU) /*!< Lowest priority mailbox 1 flag */ #define CAN_FLAG_LOW2 (0x0000051FU) /*!< Lowest priority mailbox 2 flag */ /* Receive Flags */ #define CAN_FLAG_FF0 (0x00000203U) /*!< RX FIFO 0 Full flag */ #define CAN_FLAG_FOV0 (0x00000204U) /*!< RX FIFO 0 Overrun flag */ #define CAN_FLAG_FF1 (0x00000403U) /*!< RX FIFO 1 Full flag */ #define CAN_FLAG_FOV1 (0x00000404U) /*!< RX FIFO 1 Overrun flag */ /* Operating Mode Flags */ #define CAN_FLAG_INAK (0x00000100U) /*!< Initialization acknowledge flag */ #define CAN_FLAG_SLAK (0x00000101U) /*!< Sleep acknowledge flag */ #define CAN_FLAG_ERRI (0x00000102U) /*!< Error flag */ #define CAN_FLAG_WKU (0x00000103U) /*!< Wake up interrupt flag */ #define CAN_FLAG_SLAKI (0x00000104U) /*!< Sleep acknowledge interrupt flag */ /* Error Flags */ #define CAN_FLAG_EWG (0x00000300U) /*!< Error warning flag */ #define CAN_FLAG_EPV (0x00000301U) /*!< Error passive flag */ #define CAN_FLAG_BOF (0x00000302U) /*!< Bus-Off flag */ /** * @} */ /** @defgroup CAN_Interrupts CAN Interrupts * @{ */ /* Transmit Interrupt */ #define CAN_IT_TX_MAILBOX_EMPTY ((uint32_t)CAN_IER_TMEIE) /*!< Transmit mailbox empty interrupt */ /* Receive Interrupts */ #define CAN_IT_RX_FIFO0_MSG_PENDING ((uint32_t)CAN_IER_FMPIE0) /*!< FIFO 0 message pending interrupt */ #define CAN_IT_RX_FIFO0_FULL ((uint32_t)CAN_IER_FFIE0) /*!< FIFO 0 full interrupt */ #define CAN_IT_RX_FIFO0_OVERRUN ((uint32_t)CAN_IER_FOVIE0) /*!< FIFO 0 overrun interrupt */ #define CAN_IT_RX_FIFO1_MSG_PENDING ((uint32_t)CAN_IER_FMPIE1) /*!< FIFO 1 message pending interrupt */ #define CAN_IT_RX_FIFO1_FULL ((uint32_t)CAN_IER_FFIE1) /*!< FIFO 1 full interrupt */ #define CAN_IT_RX_FIFO1_OVERRUN ((uint32_t)CAN_IER_FOVIE1) /*!< FIFO 1 overrun interrupt */ /* Operating Mode Interrupts */ #define CAN_IT_WAKEUP ((uint32_t)CAN_IER_WKUIE) /*!< Wake-up interrupt */ #define CAN_IT_SLEEP_ACK ((uint32_t)CAN_IER_SLKIE) /*!< Sleep acknowledge interrupt */ /* Error Interrupts */ #define CAN_IT_ERROR_WARNING ((uint32_t)CAN_IER_EWGIE) /*!< Error warning interrupt */ #define CAN_IT_ERROR_PASSIVE ((uint32_t)CAN_IER_EPVIE) /*!< Error passive interrupt */ #define CAN_IT_BUSOFF ((uint32_t)CAN_IER_BOFIE) /*!< Bus-off interrupt */ #define CAN_IT_LAST_ERROR_CODE ((uint32_t)CAN_IER_LECIE) /*!< Last error code interrupt */ #define CAN_IT_ERROR ((uint32_t)CAN_IER_ERRIE) /*!< Error Interrupt */ /** * @} */ /** * @} */ /* Exported macros -----------------------------------------------------------*/ /** @defgroup CAN_Exported_Macros CAN Exported Macros * @{ */ /** @brief Reset CAN handle state * @param __HANDLE__ CAN handle. * @retval None */ #define __HAL_CAN_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CAN_STATE_RESET) /** * @brief Enable the specified CAN interrupts. * @param __HANDLE__ CAN handle. * @param __INTERRUPT__ CAN Interrupt sources to enable. * This parameter can be any combination of @arg CAN_Interrupts * @retval None */ #define __HAL_CAN_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__)) /** * @brief Disable the specified CAN interrupts. * @param __HANDLE__ CAN handle. * @param __INTERRUPT__ CAN Interrupt sources to disable. * This parameter can be any combination of @arg CAN_Interrupts * @retval None */ #define __HAL_CAN_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__)) /** @brief Check if the specified CAN interrupt source is enabled or disabled. * @param __HANDLE__ specifies the CAN Handle. * @param __INTERRUPT__ specifies the CAN interrupt source to check. * This parameter can be a value of @arg CAN_Interrupts * @retval The state of __IT__ (TRUE or FALSE). */ #define __HAL_CAN_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) & (__INTERRUPT__)) /** @brief Check whether the specified CAN flag is set or not. * @param __HANDLE__ specifies the CAN Handle. * @param __FLAG__ specifies the flag to check. * This parameter can be one of @arg CAN_flags * @retval The state of __FLAG__ (TRUE or FALSE). */ #define __HAL_CAN_GET_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8U) == 5U)? ((((__HANDLE__)->Instance->TSR) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 2U)? ((((__HANDLE__)->Instance->RF0R) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 4U)? ((((__HANDLE__)->Instance->RF1R) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 1U)? ((((__HANDLE__)->Instance->MSR) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 3U)? ((((__HANDLE__)->Instance->ESR) & (1U << ((__FLAG__) & CAN_FLAG_MASK))) == (1U << ((__FLAG__) & CAN_FLAG_MASK))): 0U) /** @brief Clear the specified CAN pending flag. * @param __HANDLE__ specifies the CAN Handle. * @param __FLAG__ specifies the flag to check. * This parameter can be one of the following values: * @arg CAN_FLAG_RQCP0: Request complete MailBox 0 Flag * @arg CAN_FLAG_TXOK0: Transmission OK MailBox 0 Flag * @arg CAN_FLAG_ALST0: Arbitration Lost MailBox 0 Flag * @arg CAN_FLAG_TERR0: Transmission error MailBox 0 Flag * @arg CAN_FLAG_RQCP1: Request complete MailBox 1 Flag * @arg CAN_FLAG_TXOK1: Transmission OK MailBox 1 Flag * @arg CAN_FLAG_ALST1: Arbitration Lost MailBox 1 Flag * @arg CAN_FLAG_TERR1: Transmission error MailBox 1 Flag * @arg CAN_FLAG_RQCP2: Request complete MailBox 2 Flag * @arg CAN_FLAG_TXOK2: Transmission OK MailBox 2 Flag * @arg CAN_FLAG_ALST2: Arbitration Lost MailBox 2 Flag * @arg CAN_FLAG_TERR2: Transmission error MailBox 2 Flag * @arg CAN_FLAG_FF0: RX FIFO 0 Full Flag * @arg CAN_FLAG_FOV0: RX FIFO 0 Overrun Flag * @arg CAN_FLAG_FF1: RX FIFO 1 Full Flag * @arg CAN_FLAG_FOV1: RX FIFO 1 Overrun Flag * @arg CAN_FLAG_WKUI: Wake up Interrupt Flag * @arg CAN_FLAG_SLAKI: Sleep acknowledge Interrupt Flag * @retval None */ #define __HAL_CAN_CLEAR_FLAG(__HANDLE__, __FLAG__) \ ((((__FLAG__) >> 8U) == 5U)? (((__HANDLE__)->Instance->TSR) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 2U)? (((__HANDLE__)->Instance->RF0R) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 4U)? (((__HANDLE__)->Instance->RF1R) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): \ (((__FLAG__) >> 8U) == 1U)? (((__HANDLE__)->Instance->MSR) = (1U << ((__FLAG__) & CAN_FLAG_MASK))): 0U) /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CAN_Exported_Functions CAN Exported Functions * @{ */ /** @addtogroup CAN_Exported_Functions_Group1 Initialization and de-initialization functions * @brief Initialization and Configuration functions * @{ */ /* Initialization and de-initialization functions *****************************/ HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef *hcan); void HAL_CAN_MspInit(CAN_HandleTypeDef *hcan); void HAL_CAN_MspDeInit(CAN_HandleTypeDef *hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group2 Configuration functions * @brief Configuration functions * @{ */ /* Configuration functions ****************************************************/ HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef *hcan, CAN_FilterTypeDef *sFilterConfig); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group3 Control functions * @brief Control functions * @{ */ /* Control functions **********************************************************/ HAL_StatusTypeDef HAL_CAN_Start(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_Stop(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_RequestSleep(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan); uint32_t HAL_CAN_IsSleepActive(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_AddTxMessage(CAN_HandleTypeDef *hcan, CAN_TxHeaderTypeDef *pHeader, uint8_t aData[], uint32_t *pTxMailbox); HAL_StatusTypeDef HAL_CAN_AbortTxRequest(CAN_HandleTypeDef *hcan, uint32_t TxMailboxes); uint32_t HAL_CAN_GetTxMailboxesFreeLevel(CAN_HandleTypeDef *hcan); uint32_t HAL_CAN_IsTxMessagePending(CAN_HandleTypeDef *hcan, uint32_t TxMailboxes); uint32_t HAL_CAN_GetTxTimestamp(CAN_HandleTypeDef *hcan, uint32_t TxMailbox); HAL_StatusTypeDef HAL_CAN_GetRxMessage(CAN_HandleTypeDef *hcan, uint32_t RxFifo, CAN_RxHeaderTypeDef *pHeader, uint8_t aData[]); uint32_t HAL_CAN_GetRxFifoFillLevel(CAN_HandleTypeDef *hcan, uint32_t RxFifo); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group4 Interrupts management * @brief Interrupts management * @{ */ /* Interrupts management ******************************************************/ HAL_StatusTypeDef HAL_CAN_ActivateNotification(CAN_HandleTypeDef *hcan, uint32_t ActiveITs); HAL_StatusTypeDef HAL_CAN_DeactivateNotification(CAN_HandleTypeDef *hcan, uint32_t InactiveITs); void HAL_CAN_IRQHandler(CAN_HandleTypeDef *hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group5 Callback functions * @brief Callback functions * @{ */ /* Callbacks functions ********************************************************/ void HAL_CAN_TxMailbox0CompleteCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_TxMailbox1CompleteCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_TxMailbox2CompleteCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_TxMailbox0AbortCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_TxMailbox1AbortCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_TxMailbox2AbortCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_RxFifo0FullCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_RxFifo1MsgPendingCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_RxFifo1FullCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_SleepCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_WakeUpFromRxMsgCallback(CAN_HandleTypeDef *hcan); void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan); /** * @} */ /** @addtogroup CAN_Exported_Functions_Group6 Peripheral State and Error functions * @brief CAN Peripheral State functions * @{ */ /* Peripheral State and Error functions ***************************************/ HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef *hcan); uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan); HAL_StatusTypeDef HAL_CAN_ResetError(CAN_HandleTypeDef *hcan); /** * @} */ /** * @} */ /* Private types -------------------------------------------------------------*/ /** @defgroup CAN_Private_Types CAN Private Types * @{ */ /** * @} */ /* Private variables ---------------------------------------------------------*/ /** @defgroup CAN_Private_Variables CAN Private Variables * @{ */ /** * @} */ /* Private constants ---------------------------------------------------------*/ /** @defgroup CAN_Private_Constants CAN Private Constants * @{ */ #define CAN_FLAG_MASK (0x000000FFU) /** * @} */ /* Private Macros -----------------------------------------------------------*/ /** @defgroup CAN_Private_Macros CAN Private Macros * @{ */ #define IS_CAN_MODE(MODE) (((MODE) == CAN_MODE_NORMAL) || \ ((MODE) == CAN_MODE_LOOPBACK)|| \ ((MODE) == CAN_MODE_SILENT) || \ ((MODE) == CAN_MODE_SILENT_LOOPBACK)) #define IS_CAN_SJW(SJW) (((SJW) == CAN_SJW_1TQ) || ((SJW) == CAN_SJW_2TQ) || \ ((SJW) == CAN_SJW_3TQ) || ((SJW) == CAN_SJW_4TQ)) #define IS_CAN_BS1(BS1) (((BS1) == CAN_BS1_1TQ) || ((BS1) == CAN_BS1_2TQ) || \ ((BS1) == CAN_BS1_3TQ) || ((BS1) == CAN_BS1_4TQ) || \ ((BS1) == CAN_BS1_5TQ) || ((BS1) == CAN_BS1_6TQ) || \ ((BS1) == CAN_BS1_7TQ) || ((BS1) == CAN_BS1_8TQ) || \ ((BS1) == CAN_BS1_9TQ) || ((BS1) == CAN_BS1_10TQ)|| \ ((BS1) == CAN_BS1_11TQ)|| ((BS1) == CAN_BS1_12TQ)|| \ ((BS1) == CAN_BS1_13TQ)|| ((BS1) == CAN_BS1_14TQ)|| \ ((BS1) == CAN_BS1_15TQ)|| ((BS1) == CAN_BS1_16TQ)) #define IS_CAN_BS2(BS2) (((BS2) == CAN_BS2_1TQ) || ((BS2) == CAN_BS2_2TQ) || \ ((BS2) == CAN_BS2_3TQ) || ((BS2) == CAN_BS2_4TQ) || \ ((BS2) == CAN_BS2_5TQ) || ((BS2) == CAN_BS2_6TQ) || \ ((BS2) == CAN_BS2_7TQ) || ((BS2) == CAN_BS2_8TQ)) #define IS_CAN_PRESCALER(PRESCALER) (((PRESCALER) >= 1U) && ((PRESCALER) <= 1024U)) #define IS_CAN_FILTER_ID_HALFWORD(HALFWORD) ((HALFWORD) <= 0xFFFFU) #if defined(CAN2) #define IS_CAN_FILTER_BANK_DUAL(BANK) ((BANK) <= 27U) #endif #define IS_CAN_FILTER_BANK_SINGLE(BANK) ((BANK) <= 13U) #define IS_CAN_FILTER_MODE(MODE) (((MODE) == CAN_FILTERMODE_IDMASK) || \ ((MODE) == CAN_FILTERMODE_IDLIST)) #define IS_CAN_FILTER_SCALE(SCALE) (((SCALE) == CAN_FILTERSCALE_16BIT) || \ ((SCALE) == CAN_FILTERSCALE_32BIT)) #define IS_CAN_FILTER_ACTIVATION(ACTIVATION) (((ACTIVATION) == CAN_FILTER_DISABLE) || \ ((ACTIVATION) == CAN_FILTER_ENABLE)) #define IS_CAN_FILTER_FIFO(FIFO) (((FIFO) == CAN_FILTER_FIFO0) || \ ((FIFO) == CAN_FILTER_FIFO1)) #define IS_CAN_TX_MAILBOX(TRANSMITMAILBOX) (((TRANSMITMAILBOX) == CAN_TX_MAILBOX0 ) || \ ((TRANSMITMAILBOX) == CAN_TX_MAILBOX1 ) || \ ((TRANSMITMAILBOX) == CAN_TX_MAILBOX2 )) #define IS_CAN_TX_MAILBOX_LIST(TRANSMITMAILBOX) ((TRANSMITMAILBOX) <= (CAN_TX_MAILBOX0 | CAN_TX_MAILBOX1 | CAN_TX_MAILBOX2)) #define IS_CAN_STDID(STDID) ((STDID) <= 0x7FFU) #define IS_CAN_EXTID(EXTID) ((EXTID) <= 0x1FFFFFFFU) #define IS_CAN_DLC(DLC) ((DLC) <= 8U) #define IS_CAN_IDTYPE(IDTYPE) (((IDTYPE) == CAN_ID_STD) || \ ((IDTYPE) == CAN_ID_EXT)) #define IS_CAN_RTR(RTR) (((RTR) == CAN_RTR_DATA) || ((RTR) == CAN_RTR_REMOTE)) #define IS_CAN_RX_FIFO(FIFO) (((FIFO) == CAN_RX_FIFO0) || ((FIFO) == CAN_RX_FIFO1)) #define IS_CAN_IT(IT) ((IT) <= (CAN_IT_TX_MAILBOX_EMPTY | CAN_IT_RX_FIFO0_MSG_PENDING | \ CAN_IT_RX_FIFO0_FULL | CAN_IT_RX_FIFO0_OVERRUN | \ CAN_IT_RX_FIFO1_MSG_PENDING | CAN_IT_RX_FIFO1_FULL | \ CAN_IT_RX_FIFO1_OVERRUN | CAN_IT_WAKEUP | \ CAN_IT_SLEEP_ACK | CAN_IT_ERROR_WARNING | \ CAN_IT_ERROR_PASSIVE | CAN_IT_BUSOFF | \ CAN_IT_LAST_ERROR_CODE | CAN_IT_ERROR)) /** * @} */ /* End of private macros -----------------------------------------------------*/ /** * @} */ #endif /* CAN1 */ /** * @} */ #ifdef __cplusplus } #endif #endif /* STM32F1xx_HAL_CAN_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ 求大佬指点哪里错了。。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、PDF搜索网站推荐 对于大部
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
Vue + Spring Boot 项目实战(十四):用户认证方案与完善的访问拦截
本篇文章主要讲解 token、session 等用户认证方案的区别并分析常见误区,以及如何通过前后端的配合实现完善的访问拦截,为下一步权限控制的实现打下基础。
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入  假设现有4个人
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
SQL-小白最佳入门sql查询一
一 说明 如果是初学者,建议去网上寻找安装Mysql的文章安装,以及使用navicat连接数据库,以后的示例基本是使用mysql数据库管理系统; 二 准备前提 需要建立一张学生表,列分别是id,名称,年龄,学生信息;本示例中文章篇幅原因SQL注释略; 建表语句: CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // dosho
漫话:什么是平衡(AVL)树?这应该是把AVL树讲的最好的文章了
这篇文章通过对话的形式,由浅入深带你读懂 AVL 树,看完让你保证理解 AVL 树的各种操作,如果觉得不错,别吝啬你的赞哦。 1、若它的左子树不为空,则左子树上所有的节点值都小于它的根节点值。 2、若它的右子树不为空,则右子树上所有的节点值均大于它的根节点值。 3、它的左右子树也分别可以充当为二叉查找树。 例如: 例如,我现在想要查找数值为14的节点。由于二叉查找树的特性,我们可...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
开源并不是你认为的那些事
点击上方蓝字 关注我们开源之道导读所以 ————想要理清开源是什么?先要厘清开源不是什么,名正言顺是句中国的古代成语,概念本身的理解非常之重要。大部分生物多样性的起源,...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
      11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下
《C++ Primer》学习笔记(六):C++模块设计——函数
专栏C++学习笔记 《C++ Primer》学习笔记/习题答案 总目录 https://blog.csdn.net/TeFuirnever/article/details/100700212 —————————————————————————————————————————————————————— 《C++ Primer》习题参考答案:第6章 - C++模块设计——函数 文章目录专栏C+...
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
so easy! 10行代码写个"狗屁不通"文章生成器
前几天,GitHub 有个开源项目特别火,只要输入标题就可以生成一篇长长的文章。背后实现代码一定很复杂吧,里面一定有很多高深莫测的机器学习等复杂算法不过,当我看了源代码之后这程序不到50
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
相关热词 基于c#波形控件 c# 十进制转十六进制 对文件aes加密vc# c#读取栈中所有的值 c# rsa256加密 好 学c# 还是c++ c# 和java的差距 c# curl网络框架 c# https证书请求 c# 中崎
立即提问