C# 使用ResponseStream下载文件部分,实际下载的文件部分比我要下载的文件部分小,什么原因?

C# 使用response.GetResponseStream下载文件某一部分,实际下载的文件部分 比 我要下载的文件部分小,什么原因?我要下载文件前50000000字节,实际下载只有49,909,760字节,代码如下:

 class Program
    {
        public static void Main(string[] args)
        {
            PartDownload("http://192.168.1.104/jkbd.exe", @"C:\Users\WYQ\Desktop\Test\split\dt1.sp", 0, 50000000);
        }
        private static void PartDownload(string url, string filePath, Int64 start, Int64 end)
        {
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.AddRange("bytes", start, end);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            CopyStream(responseStream, fs);
            responseStream.Close();
            response.Close();
            fs.Close();
        }
        public static void CopyStream(Stream inputStream, Stream outputStream, int bufferSize = 512*200)
        {
            BufferedStream bufferedInputStream = new BufferedStream(inputStream, bufferSize);
            BufferedStream bufferedOutputStream = new BufferedStream(outputStream, bufferSize);
            byte[] bs = new byte[bufferSize];
            int len = 0;
            while ((len = bufferedInputStream.Read(bs, 0, bufferSize)) != 0)
            {
                bufferedOutputStream.Write(bs, 0, len);
            }
        }
    }

下载结果:
图片说明
只有49,909,760字节,而我要下载文件前50000000字节。这个是什么原因导致的?

3个回答

一个文件在不同的计算机上显示有可能不同

qq_33530738
qq_33530738 刚刚将copystream中bufferedstream去掉,直接使用stream读写,就没有数据丢失
4 年多之前 回复
qq_33530738
qq_33530738 我是在同一台计算机上做的,服务器是我电脑windows8.1的iis8
4 年多之前 回复

我是在同一台计算机上做的,服务器是我电脑windows8.1的iis8

如果不影响打开或者使用 这些差距可以忽略了
因为上传文件与下载文件是以字节流的方式进行 在进行字节流转换的过程中难免会丢失
就如同你用10/3.0会得到3.33333333333,然后你再乘以3 只能得到9.999999999而得不到10是一个道理

qq_33530738
qq_33530738 刚刚将copystream中bufferedstream去掉,直接使用stream读写,就没有数据丢失
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
c#数据流指定位置,按行输出

一个数组形式为:EB3C2D04.........想从标志0E31后288个bit处开始读,到标志043A处停止。然后把每个符合这样条件的数据按行输出

将C#程序转化成java程序

public String postDataToUrl(String PostData, String PostUrl, String PostEncod, boolean UrlEncode, boolean ToBase64, String contentType) { Encoding RequstEncod = Encoding.GetEncoding("UTF-8"); if (PostEncod != null) { RequstEncod = Encoding.GetEncoding(PostEncod); } //URL编码 if (UrlEncode) { PostData = HttpUtility.UrlEncode(PostData); } byte[] data = RequstEncod.GetBytes(PostData); //进行64位编码 if (ToBase64) { data = RequstEncod.GetBytes(Convert.ToBase64String(data)); } ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate xc, System.Security.Cryptography.X509Certificates.X509Chain c, System.Net.Security.SslPolicyErrors se) { return true; }; //创建请求对象 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(PostUrl); if (httpWebRequest == null) { return ""; } #region 填充httpWebRequest的基本信息 httpWebRequest.ContentType = contentType; httpWebRequest.Method = "Post"; #endregion httpWebRequest.ContentLength = data.Length; try { Stream RequestStream = httpWebRequest.GetRequestStream(); RequestStream.Write(data, 0, data.Length); RequestStream.Close(); #region 接收返回数据 Stream ResponseStream; string stringResponse = string.Empty; ResponseStream = httpWebRequest.GetResponse().GetResponseStream(); using (StreamReader sr = new StreamReader(ResponseStream, RequstEncod)) { stringResponse = sr.ReadToEnd(); } ResponseStream.Close(); return stringResponse; #endregion } catch (Exception ex) { return ex.Message; } }

使用c#将params设置为Web服务

<div class="post-text" itemprop="text"> <p>i can't set params to my web service this is my code in php :</p> <pre><code>$myValue = $_POST['myValue']; </code></pre> <p>and this is my C# Code :</p> <pre><code>void POST(string url, string jsonContent) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); Byte[] byteArray = encoding.GetBytes("myValue=" + jsonContent); request.ContentLength = byteArray.Length; request.ContentType = @"application/json"; using (Stream dataStream = request.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); } long length = 0; try { //request.GetResponse(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { length = response.ContentLength; using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); string WSReturned = reader.ReadToEnd(); } } } catch (WebException ex) { //Nothing... } } </code></pre> <p>i tested "&amp;myValue=" and return null again</p> <p>This is my PHP Code :</p> <pre><code>&lt;?php if (isset($_POST['NewArray'])) { $NewArray = $_POST['NewArray']; } else { $NewArray = "Not"; } echo $NewArray;?&gt; </code></pre> </div>

GetResponseStream只能使用一次的问题。

我用HttpWebRequest读取了一个网页后,读取的内容保存在了HttpWebResponse里面。 我后续要对HttpWebResponse的数据进行分析,可以HttpWebResponse里的GetResponseStream只能读取一次,不能反复使用,这个怎么解决? 尽量不要再次对原始网页进行下载。

为什么下面的代码只能下载一行数据?

``` private async void 下载保存测试股票数据文件(string stockCode) { //设定下载时间段 DateTime endDate = DateTime.Now; DateTime startDate = endDate.AddDays(-30); string filePathName = "C:\\TEMP\\" + stockCode + ".csv"; string uri = string.Format("http://quotes.money.163.com/service/chddata.html?code={0}&start={1}&end={2}&fields=TCLOSE;HIGH;LOW;TOPEN;TURNOVER;VOTURNOVER", stockCode, startDate.ToString("yyyyMMdd"), endDate.ToString("yyyyMMdd")); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); using (StreamReader srWeb = new StreamReader(responseStream, Encoding.GetEncoding("gb2312"))) { string text = await srWeb.ReadToEndAsync(); //或者取消异步直接string text = srWeb.ReadToEnd(); //或者循环读取一行While(text = srWeb.ReadLine() != null) Console.WriteLine(text); } } ``` //即使使用ReadLine(),第一次有一行数据,第二次读行就为空了,啥道理啊?困住了,大家能否救救我,跪谢! //用uri的实际字符串手动在浏览器里能直接下载到完整的多行数据,比如: http://quotes.money.163.com/service/chddata.html?code=0601336&start=20160616&end=20160716&fields=TCLOSE;HIGH;LOW;TOPEN;TURNOVER;VOTURNOVER

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#模拟登录中国联通获取用户通话详单

我写一个根据手机号码和服务密码自动登录中国联通官网 然后获取通话详单json的类,第一步模拟登录返回的数据没有问题 但是第二步获取通话详单的时候总是报500错误 有人知道解决方法吗? public static string GetCalldetails(string userName, string password) { string content=""; CookieContainer cookie = new CookieContainer(); string postUrl = "https://uac.10010.com/portal/Service/MallLogin?callback=jQuery17202691898950318097_1403425938090&redirectURL=http://www.10010.com&userName="+userName+"&password="+password+"&pwdType=01&productType=01&redirectType=01&rememberMe=1"; HttpWebRequest httpRequset = (HttpWebRequest)WebRequest.Create(postUrl); httpRequset.CookieContainer = cookie;//设置cookie httpRequset.Method = "GET"; httpRequset.ContentType = "text/html;charset=UTF-8"; HttpWebResponse httpresponse = (HttpWebResponse)httpRequset.GetResponse(); Stream myResponseStream = httpresponse.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); if (Convert.ToInt32(httpresponse.StatusCode) == 200) { if (retString.Contains("resultCode:\"0000\"")) { string billurl = "http://iservice.10010.com/e3/static/query/callDetail?_=1450840337718&menuid=000100030001"; string strdata = "pageNo=1&pageSize=100&beginDate=2015-12-01&endDate=2015-12-23"; byte[] byteArray = Encoding.UTF8.GetBytes(strdata); //string billurl = "http://iservice.10010.com/e3/static/check/checklogin/?_=1450857473494"; // HttpWebRequest Requset = (HttpWebRequest)WebRequest.Create(billurl); HttpWebRequest Requset = (HttpWebRequest)WebRequest.Create(billurl); Requset.Method = "POST"; Requset.CookieContainer = cookie; Requset.ContentType = "application/x-www-form-urlencoded"; Stream stream = Requset.GetRequestStream(); using (StreamWriter myStreamWriter = new StreamWriter(stream, Encoding.GetEncoding("UTF-8"))) { myStreamWriter.Write(byteArray); } HttpWebResponse response = (HttpWebResponse)Requset.GetResponse(); //if (Convert.ToInt32(response.StatusCode) == 200) //{ using (Stream responsestream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(responsestream, Encoding.GetEncoding("utf-8"))) { content = sr.ReadToEnd(); //return content; } } return content; } else { return "登录失败:" + retString + ""; } } else { int num = Convert.ToInt32(httpresponse.StatusCode); return "数据传输失败:" + num+""; } }

发送时发生错误,上面一段是人家接口PHP的示例代码,下面是做成C#的,我执行下面的C#时提示基础连接已经关闭,请问是哪里不对?

```<?php define('APPID', '<ID>'); define('SECRET', '<PW>'); define('CALLBACK_URL', '<CALLBACKURL>'); define('TOKEN_URL', '***'); $header = [ 'Content-Type: application/x-www-form-urlencoded', 'Authorization: Basic ' . base64_encode(APPID . ':' . SECRET), ]; $param = array( 'code' => <code>, 'grant_type' => 'authorization_code', 'redirect_uri' => CALLBACK_URL, ); $ch = curl_init(TOKEN_URL); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param)); $response = curl_exec($ch); curl_close($ch); $token = json_decode($response, true); var_dump($token); ?> //我这样提示基础连接已经关闭,发送时发生错误         const string APPID = "***"; const string SECRET = "***"; const string CALLBACK_URL = "***"; const string TOKEN_URL = "***"; string jsonParam = "code=***&grant_type=authorization_code&redirect_uri=" + CALLBACK_URL; byte[] data = Encoding.UTF8.GetBytes(jsonParam); string base64Credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(APPID + ":" + SECRET)); HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(TOKEN_URL); hwr.ContentType = "application/x-www-form-urlencoded"; hwr.Headers.Add("Authorization", "Basic " + base64Credentials); hwr.Method = "POST"; hwr.ContentLength = data.Length; Stream dataStream = hwr.GetRequestStream(); dataStream.Write(data, 0, data.Length); WebResponse response = hwr.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); string content = reader.ReadToEnd(); ```

Android urlconnection 上传文件

我通过Android 的urlConnection去上传文件,但是Spring MVC却接收不到,但是使用 jodd http库就可以。 常数代码: ``` private static final String END = "\r\n"; private static final String PREFIX = "--"; private static final String BOUNDARY = "***************"; private static final String REQUEST_POST = "POST"; private static final int TIME_OUT = 5000; private static final String PROPERTY_KEY_CONNECTION = "Connection"; private static final String PROPERTY_KEY_CHARSET = "Charset"; private static final String PROPERTY_KEY_COOKIE = "Cookie"; private static final String PROPERTY_KEY_CONTENT_TYPE = "Content-Type"; private static final String PROPERTY_VALUE_CONNECTION = "Keep-Alive"; private static final String PROPERTY_VALUE_CHARSET = "UTF-8"; private static final String PROPERTY_VALUE_REQUEST_CONTENT_TYPE = "multipart/json"; private static final String PROPERTY_VALUE_FILE_UPLOAD_CONTENT_TYPE = "multipart/form-data;boundary=" + BOUNDARY; private static final String PROPERTY_KEY_ACCEPT = "Accept"; private static final String PROPERTY_VALUE_ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; ``` 自己定义的文件上传: ``` //这里是之前我上传用的方法 try { mURL = new URL(FeedbackConst.FeedbackUrl.URL_MAIN + FeedbackConst.FeedbackUrl.URL_SUB_UPLOAD); LogUtils.i(FeedbackConst.FeedbackUrl.URL_MAIN + FeedbackConst.FeedbackUrl.URL_SUB_UPLOAD); mHttpURLConnection = (HttpURLConnection) mURL.openConnection(); //set properties mHttpURLConnection.setDoInput(true); mHttpURLConnection.setDoOutput(true); mHttpURLConnection.setUseCaches(false); String sessionId = getSessionIdFromSQLite(); mHttpURLConnection.setRequestProperty(PROPERTY_KEY_COOKIE, sessionId); mHttpURLConnection.setRequestMethod(REQUEST_POST); mHttpURLConnection.setRequestProperty(PROPERTY_KEY_CONNECTION, PROPERTY_VALUE_CONNECTION); mHttpURLConnection.setRequestProperty(PROPERTY_KEY_CHARSET, PROPERTY_VALUE_CHARSET); mHttpURLConnection.setRequestProperty(PROPERTY_KEY_CONTENT_TYPE, PROPERTY_VALUE_FILE_UPLOAD_CONTENT_TYPE); mHttpURLConnection.addRequestProperty(PROPERTY_KEY_ACCEPT, PROPERTY_VALUE_ACCEPT); DataOutputStream uploadFileOutputStream = new DataOutputStream(mHttpURLConnection.getOutputStream()); int length; Iterator<String> filenames = file.keys(); String filename = filenames.next(); LogUtils.i("file name : " + filename); String filePath = file.getString(filename); LogUtils.i("file path : " + filePath); File uploadFile = new File(filePath); FileInputStream fileInputStream = new FileInputStream(uploadFile); //DataInputStream dataInputStream = new DataInputStream(fileInputStream); LogUtils.i(LOG_TAG, "here is running!"); if (null == filename) { filename = filePath.substring(filePath.lastIndexOf("/") + 1); } //here may be is wrong uploadFileOutputStream.writeBytes(END + PREFIX + BOUNDARY + PREFIX + END); uploadFileOutputStream.writeBytes("Content-Disposition: form-data;" + "name=\"file\";filename=\"" + filename + "\"" + END); //uploadFileOutputStream.writeBytes("Content-Type: application/octet-stream;charset=utf-8" + END); uploadFileOutputStream.writeBytes(END); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; LogUtils.i(LOG_TAG, "文件大小 : " + fileInputStream.available()); while (-1 != (length = fileInputStream.read(buffer))) { uploadFileOutputStream.write(buffer, 0, length); } fileInputStream.close(); uploadFileOutputStream.writeBytes(END); uploadFileOutputStream.writeBytes(PREFIX + BOUNDARY + PREFIX + END); uploadFileOutputStream.flush(); uploadFileOutputStream.close(); float code = mHttpURLConnection.getResponseCode(); LogUtils.e("response Code : " + code); if (200 == (int) code) { InputStream responseStream = mHttpURLConnection.getInputStream(); BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseStream)); StringBuffer responseBuffer = new StringBuffer(); String tmp; while (null != (tmp = responseReader.readLine())) { responseBuffer.append(tmp); } LogUtils.i(LOG_TAG, responseBuffer.toString()); responseStream.close(); } else { LogUtils.e("server response error code : " + code); return null; } } catch (MalformedURLException e) { LogUtils.e(LOG_TAG, e.getMessage()); throw new FeedbackException(e.hashCode(), e.getMessage()); } catch (IOException e) { LogUtils.e(LOG_TAG, "IOException : " + e.getMessage()); throw new FeedbackException(e.hashCode(), e.getMessage()); } catch (JSONException e) { LogUtils.e(LOG_TAG, e.getMessage()); throw new FeedbackException(e.hashCode(), e.getMessage()); } ``` 使用jodd库进行上传: ``` Iterator<String> filenames = file.keys(); jodd.http.HttpRequest req = jodd.http.HttpRequest.post(FeedbackConst.FeedbackUrl.URL_MAIN + FeedbackConst.FeedbackUrl.URL_SUB_UPLOAD) .accept(PROPERTY_VALUE_ACCEPT) .cookies(new Cookie(getSessionIdFromSQLite())); while (filenames.hasNext()) { String filename = filenames.next(); LogUtils.i("file name : " + filename); try { req.form(filename, new File(file.getString(filename))); } catch (JSONException e) { e.printStackTrace(); } } jodd.http.HttpResponse httpResponse = req.send(); LogUtils.i("url : " + req.url()); LogUtils.i("response code : " + httpResponse.statusCode() + ""); String value = httpResponse.charset("utf-8").bodyText(); LogUtils.i("return length : " + value.length()); value = value.replaceAll("\r|\n", ""); try { mResponseJSONObject = new JSONObject(value); } catch (JSONException e) { throw new FeedbackException(e.hashCode(), e.getMessage()); } ```

中国银行接口后台POST提交

中国银行退款接口,在后台POST提交不走页面。在请求是报错请求被中止: 未能创建 SSL/TLS 安全通道。代码如下 string Number = CreateRandomCode(30); posturl = "https://ebspay.boc.cn/PGWPortal/RefundOrder.do"; pastData = ChinaBlankConfig.merchantNo + "|" + Number + "|" + "001" + "|" + 0.01 + "|" + "20121206SHKF000004"; byte[] _bytedata = System.Text.Encoding.UTF8.GetBytes(pastData); string _strSignData = PKCS7Tool.SignatureMessage(cerPath, cerWord, _bytedata, string.Empty); string _singDate = "merchantNo=" + ChinaBlankConfig.merchantNo + "&mRefundSeq=" + Number + "&curCode=001" + "&refundAmount=" + 0.01 + "&orderNo=20121206SHKF000004" + "&signData=" + _strSignData; string str = RequestAndResponse(posturl, _singDate); //初始化请求对象 var request = WebRequest.Create(url) as HttpWebRequest; //X509证书 //X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(cerPath, "111111", X509KeyStorageFlags.MachineKeySet); //request.ClientCertificates.Add(cert); X509Certificate cert = new System.Security.Cryptography.X509Certificates.X509Certificate(cerPath, "111111"); X509Certificate cert2 = new System.Security.Cryptography.X509Certificates.X509Certificate(keyStorePath); request.ClientCertificates.Add(cert2); request.ClientCertificates.Add(cert); request.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; //设定验证回调(总是同意) ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = Encoding.UTF8.GetByteCount(postData); request.Timeout = 300000; request.ReadWriteTimeout = 300000; //将来数据内容写入传输数据流中,并传输 using (var requestStream = request.GetRequestStream()) { using (var streamWriter = new StreamWriter(requestStream)) { streamWriter.Write(postData); } } //初始化响应对象 var response = request.GetResponse() as HttpWebResponse; //从传输流中对象返回的数据 using (var responseStream = response.GetResponseStream()) { using (var streamReader = new StreamReader(responseStream)) { return streamReader.ReadToEnd(); } }

使用PHP / JS动态填充上传文件的网页

<div class="post-text" itemprop="text"> <p>I have been tasked with modifying a page so that it accepts an uploaded file and parses the contents of that file to display it in a particular format.</p> <p>I have code that parses the file - but currently it reads a static file on the server and reads it as a string. Instead I want the contents of the file to populate the string after upload.</p> <p>What's the best way to accomplish this using PHP/JS. I would prefer not to use PHP at all if possible, but it's fine if I have to.</p> <p>Other options are also welcome.</p> <p>Thanks</p> <p>Edit:</p> <p>Thanks - I will post the code shortly as I'm yet making some changes to it.</p> <p>This might be a stupid question, but I'm not familiar with AJAX.</p> <p>Does the file have to be uploaded to any location, or can it be temporarily housed in a variable. </p> <p>The file I need to use is </p> <p><a href="http://distributome.avinashc.com/howardL/scripts/distributome.js" rel="nofollow">http://distributome.avinashc.com/howardL/scripts/distributome.js</a></p> <p>In particular the lines xmlDoc = xmlhttp.responseXML;</p> <p>I am opening the file "Distributome.xml" using the operation</p> <p>xmlhttp.open("GET","Distributome.xml",false);</p> <p>Instead I want to populate it using an XML file (or two) that the user uploads.</p> <p>As another part of the task; I need to use two files so that they contain different data; so for now I am just appending the two files - in the lines that I have commented.</p> <p>Edit:</p> <pre><code> { /* Split into distributions and relations - but append them xmlhttp.open("GET","Distributome.xml",false); xmlhttp.send(); if (!xmlhttp.responseXML.documentElement &amp;&amp; xmlhttp.responseStream) xmlhttp.responseXML.load(xmlhttp.responseStream); xmlDoc = xmlhttp.responseXML; xmlhttp.open("GET","Distributome-references.xml",false); xmlhttp.send(); if (!xmlhttp.responseXML.documentElement &amp;&amp; xmlhttp.responseStream) xmlhttp.responseXML.load(xmlhttp.responseStream); xmlDoc = xmlDoc+xmlhttp.responseXML; */ getURLParameters(); /*** Read in and parse the Distributome.xml DB ***/ var xmlhttp=createAjaxRequest(); xmlhttp.open("GET","Distributome.xml",false); xmlhttp.send(); if (!xmlhttp.responseXML.documentElement &amp;&amp; xmlhttp.responseStream) xmlhttp.responseXML.load(xmlhttp.responseStream); xmlDoc = xmlhttp.responseXML; try{ DistributomeXML_Objects=xmlDoc.documentElement.childNodes; }catch(error){ DistributomeXML_Objects=xmlDoc.childNodes; } traverseXML(false, null, DistributomeXML_Objects, distributome.nodes, distributome.edges, distributome.references, distributomeNodes, referenceNodes); xmlhttp=createAjaxRequest(); xmlhttp.open("GET","Distributome.xml.pref",false); xmlhttp.send(); if (!xmlhttp.responseXML.documentElement &amp;&amp; xmlhttp.responseStream) xmlhttp.responseXML.load(xmlhttp.responseStream); var ontologyOrder = xmlhttp.responseXML; getOntologyOrderArray(ontologyOrder); } </code></pre> <p>Edit:</p> <p>I am not uploading the file to the server; instead I just want the content to be parsed when the user uploads - locally.</p> </div>

将C#SOAP Post请求转换为PHP SOAP Post请求

<div class="post-text" itemprop="text"> <p>The C# code looks like this:</p> <pre><code>private static string SendSoapRequest(string request, string destinationUrl) { string soapRequest = String.Format("&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;" + "&lt;soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"&gt;" + "&lt;soap:Body&gt;{0}&lt;/soap:Body&gt;&lt;/soap:Envelope&gt;", request); HttpWebRequest req = (HttpWebRequest) WebRequest.Create(destinationUrl); byte[] buffer = Encoding.UTF8.GetBytes(soapRequest); req.Method = "POST"; req.ContentType = "application/soap+xml"; req.ContentLength = buffer.Length; req.CookieContainer = new CookieContainer(); // enable cookies req.Referer = "localhost"; req.Credentials = CredentialCache.DefaultCredentials; Stream reqst = req.GetRequestStream(); // add form data to request stream reqst.Write(buffer, 0, buffer.Length); reqst.Flush(); reqst.Close(); HttpWebResponse res = (HttpWebResponse) req.GetResponse(); Stream responseStream = res.GetResponseStream(); if (responseStream != null) { StreamReader sr = new StreamReader(responseStream); string response = sr.ReadToEnd(); return response; } return string.Empty; } </code></pre> <p>And my effort so far, among many other variations, in PHP wihtout success:</p> <pre><code>public static function sendSoapCurl($samlMessage, $destination, $action) { $headers = array( "Content-type: application/soap+xml;charset=\"utf-8\"", "Content-length: ".strlen($samlMessage), ); if (isset($action)) { $headers[] = "SOAPAction: $action"; } // $samlMessage = utf8_encode($samlMessage); // PHP cURL for https connection with auth $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_URL, $destination); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $samlMessage); // the SOAP request curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // get soap response $soapresponsexml = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode != 200) { print_r("Status code: ".$httpCode." "); print_r($soapresponsexml);exit(); } if ($soapresponsexml === null || $soapresponsexml === "") { throw new \Exception('Empty SOAP response, check peer certificate.'); } try { $dom = new DOMDocument(); $dom = OneLogin_Saml2_Utils::loadXML($dom, $soapresponsexml); } catch (RuntimeException $e) { throw new \Exception('Not a SOAP response.', 0, $e); } $soapfault = self::getSOAPFault($dom); if (isset($soapfault)) { throw new \Exception($soapfault); } } </code></pre> <p>The C# code works, but I can't get it to work in PHP. Any ideas will be greatly appreciated. Thanks.</p> </div>

关于http通信的一些问题:请问大佬第一句的字符串各个部分都是什么意思

private const string UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3"; public static string PostData(string url, string data) { // Convert to bytes string strReturn = ""; try { byte[] obtPostData = Encoding.UTF8.GetBytes(data); HttpWebRequest orqRequest = (HttpWebRequest)WebRequest.Create(url); orqRequest.Timeout = 3000; orqRequest.Method = "POST"; orqRequest.UserAgent = UserAgent; orqRequest.ContentType = "application/x-www-form-urlencoded"; orqRequest.ContentLength = obtPostData.Length; orqRequest.AllowAutoRedirect = false; // Add post data to request Stream stream; using (stream = orqRequest.GetRequestStream()) { stream.Write(obtPostData, 0, obtPostData.Length); } HttpWebResponse orsResponse = (HttpWebResponse)orqRequest.GetResponse(); using (Stream responseStream = orsResponse.GetResponseStream()) { using (StreamReader streamRead = new StreamReader(responseStream, Encoding.UTF8)) { strReturn = streamRead.ReadToEnd(); } } } catch (Exception e) { strReturn = e.Message; } return strReturn; }

尝试将.zip文件从VB .NET上传到服务器时出错

<div class="post-text" itemprop="text"> <p>I´m trying to upload .zip files from my VB form to a server, but file loses header information in the process, and I´m unable to find the error/s. Debugging, i found that losed data is from header. Does anyone know why is this happening?</p> <p>My VB.NET code is:</p> <pre><code>Imports System.Text Public Class Form1 Dim hola As String = "hola" Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click HttpUploadFile("http://localhost/sitio_victor/files.php?parameter1=""value1""&amp;parameter2=" &amp; hola &amp; "", "C:\MDPScan\ParaEnviar\C001_C002_C005_01062016_092619_76CDB2BAD9582D23C1F6F4D868218D6C.zip", "file", "multipart/form-data") End Sub Private Sub HttpUploadFile( _ ByVal uri As String, _ ByVal filePath As String, _ ByVal fileParameterName As String, _ ByVal contentType As String) Dim process As New Process Dim boundary As String = "---------------------------" &amp; DateTime.Now.Ticks.ToString("x") Dim newLine As String = System.Environment.NewLine Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(newLine &amp; "--" &amp; boundary &amp; newLine) Dim request As Net.HttpWebRequest = Net.WebRequest.Create(uri) request.ContentType = "multipart/form-data; boundary=" &amp; boundary request.Method = "POST" request.KeepAlive = True request.Credentials = Net.CredentialCache.DefaultCredentials Using requestStream As IO.Stream = request.GetRequestStream() Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}" requestStream.Write(boundaryBytes, 0, boundaryBytes.Length) Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3};" Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType) MsgBox(header) Dim headerBytes As Byte() = Encoding.UTF8.GetBytes(header.ToString) requestStream.Write(headerBytes, 0, header.Length) Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read) Dim buffer(4096) As Byte Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length) Do While (bytesRead &gt; 0) requestStream.Write(buffer, 0, bytesRead) bytesRead = fileStream.Read(buffer, 0, buffer.Length) Loop End Using Dim trailer As Byte() = Encoding.ASCII.GetBytes(newLine &amp; "--" + boundary + "--" &amp; newLine) requestStream.Write(trailer, 0, trailer.Length) End Using Dim response As Net.WebResponse = Nothing Try response = request.GetResponse() Using responseStream As IO.Stream = response.GetResponseStream() Using responseReader As New IO.StreamReader(responseStream) Dim responseText = responseReader.ReadToEnd() MsgBox(responseText) End Using End Using Catch exception As Net.WebException response = exception.Response If (response IsNot Nothing) Then Using reader As New IO.StreamReader(response.GetResponseStream()) Dim responseText = reader.ReadToEnd() Diagnostics.Debug.Write(responseText) End Using response.Close() End If Finally process.Start(uri) request = Nothing End Try End Sub End Class </code></pre> <p>And PHP code is:</p> <pre><code>&lt;?php $target_dir = "C:\images"; print_r($_FILES); //print_r($_POST); print_r($_REQUEST); $target_file = $_FILES['file']['tmp_name']; if(move_uploaded_file($target_file, $target_dir. DIRECTORY_SEPARATOR . $_FILES['file']['name'])) { echo "Success"; } else { echo "Failure"; } ?&gt; </code></pre> <p>I would be grateful of have any help.</p> <p>Best regards!</p> </div>

关于HttpClient的问题,如何使用HttpClient重定向?

``` /* * HttpRequestProxy.java * * Created on November 3, 2008, 9:53 AM */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.SimpleHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; public class HttpRequestProxy { // 超时间隔 private static int connectTimeOut = 60000; // 让connectionmanager管理httpclientconnection时是否关闭连接 private static boolean alwaysClose = false; // 返回数据编码格式 private String encoding = "UTF-8"; private final HttpClient client = new HttpClient(); public HttpClient getHttpClient() { return client; } /** * 用法: HttpRequestProxy hrp = new HttpRequestProxy(); * hrp.doRequest("http://www.163.com",null,null,"gbk"); * * @param url * 请求的资源URL * @param postData * POST请求时form表单封装的数据 没有时传null * @param header * request请求时附带的头信息(header) 没有时传null * @param encoding * response返回的信息编码格式 没有时传null * @return response返回的文本数据 * @throws CustomException */ public String doRequest(String url, Map postData, Map header, String encoding) throws Exception { String responseString = null; // 头部请求信息 Header[] headers = null; if (header != null) { Set entrySet = header.entrySet(); int dataLength = entrySet.size(); headers = new Header[dataLength]; int i = 0; for (Iterator itor = entrySet.iterator(); itor.hasNext();) { Map.Entry entry = (Map.Entry) itor.next(); headers[i++] = new Header(entry.getKey().toString(), entry.getValue().toString()); } } // post方式 if (postData != null) { PostMethod postRequest = new PostMethod(url.trim()); if (headers != null) { for (int i = 0; i < headers.length; i++) { postRequest.setRequestHeader(headers[i]); } } Set entrySet = postData.entrySet(); int dataLength = entrySet.size(); NameValuePair[] params = new NameValuePair[dataLength]; int i = 0; for (Iterator itor = entrySet.iterator(); itor.hasNext();) { Map.Entry entry = (Map.Entry) itor.next(); params[i++] = new NameValuePair(entry.getKey().toString(), entry.getValue().toString()); } postRequest.setRequestBody(params); try { responseString = this.executeMethod(postRequest, encoding); } catch (Exception e) { throw e; } finally { postRequest.releaseConnection(); } } return responseString; } private String executeMethod(HttpMethod request, String encoding) throws Exception { String responseContent = null; InputStream responseStream = null; BufferedReader rd = null; try { this.getHttpClient().executeMethod(request); if (encoding != null) { responseStream = request.getResponseBodyAsStream(); rd = new BufferedReader(new InputStreamReader(responseStream, encoding)); String tempLine = rd.readLine(); StringBuffer tempStr = new StringBuffer(); String crlf = System.getProperty("line.separator"); while (tempLine != null) { tempStr.append(tempLine); tempStr.append(crlf); tempLine = rd.readLine(); } responseContent = tempStr.toString(); } else responseContent = request.getResponseBodyAsString(); Header locationHeader = request.getResponseHeader("location"); // 返回代码为302,301时,表示页面己经重定向,则重新请求location的url,这在 // 一些登录授权取cookie时很重要 if (locationHeader != null) { String redirectUrl = locationHeader.getValue(); this.doRequest(redirectUrl, null, null, null); } } catch (HttpException e) { throw new Exception(e.getMessage()); } catch (IOException e) { throw new Exception(e.getMessage()); } finally { if (rd != null) try { rd.close(); } catch (IOException e) { throw new Exception(e.getMessage()); } if (responseStream != null) try { responseStream.close(); } catch (IOException e) { throw new Exception(e.getMessage()); } } return responseContent; } /** * 特殊请求数据,这样的请求往往会出现redirect本身而出现递归死循环重定向 所以单独写成一个请求方法 * 比如现在请求的url为:http://localhost:8080/demo/index.jsp 返回代码为302 * 头部信息中location值为:http://localhost:8083/demo/index.jsp * 这时httpclient认为进入递归死循环重定向,抛出CircularRedirectException异常 * * @param url * @return * @throws CustomException */ public String doSpecialRequest(String url, int count, String encoding) throws Exception { String str = null; InputStream responseStream = null; BufferedReader rd = null; GetMethod getRequest = new GetMethod(url); // 关闭httpclient自动重定向动能 getRequest.setFollowRedirects(false); try { this.client.executeMethod(getRequest); Header header = getRequest.getResponseHeader("location"); if (header != null) { // 请求重定向后的URL,count同时加1 this.doSpecialRequest(header.getValue(), count + 1, encoding); } // 这里用count作为标志位,当count为0时才返回请求的URL文本, // 这样就可以忽略所有的递归重定向时返回文本流操作,提高性能 if (count == 0) { getRequest = new GetMethod(url); getRequest.setFollowRedirects(false); this.client.executeMethod(getRequest); responseStream = getRequest.getResponseBodyAsStream(); rd = new BufferedReader(new InputStreamReader(responseStream, encoding)); String tempLine = rd.readLine(); StringBuffer tempStr = new StringBuffer(); String crlf = System.getProperty("line.separator"); while (tempLine != null) { tempStr.append(tempLine); tempStr.append(crlf); tempLine = rd.readLine(); } str = tempStr.toString(); } } catch (HttpException e) { throw new Exception(e.getMessage()); } catch (IOException e) { throw new Exception(e.getMessage()); } finally { getRequest.releaseConnection(); if (rd != null) try { rd.close(); } catch (IOException e) { throw new Exception(e.getMessage()); } if (responseStream != null) try { responseStream.close(); } catch (IOException e) { throw new Exception(e.getMessage()); } } return str; } public static void main(String[] args) throws Exception { HttpRequestProxy hrp = new HttpRequestProxy(); Map date = new HashMap(); date.put("jyidApplet", "1"); date.put("codeNumApplet", "1"); date.put("jymxIdApplet", "447"); date.put("patientIdApplet", "1118"); String str = hrp.doRequest("http://127.0.0.1:8080/lis/mz/addTM",date, null, null); System.out.println(str); } } ```

android中,网络大图解析出NULL

如题,现在需要的是在imageView中显示一个比较大的图片(有几M大) inJustDecodeBounds这个我会用。 不过问题是出在这里: ``` HttpMethod m_request; ......此处省略 m_request.getResponseBody(); ``` 获取byte数组,这样做,小图会正常解析出Bitmap,对于大图会报OOM. 然后我换了一种办法: ``` m_responseStream = m_request.getResponseBodyAsStream(); BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; BitmapFactory.decodeStream(m_responseStream, null, opt); ...省略 opt.inJustDecodeBounds = false; m_responseStream = m_request.getResponseBodyAsStream(); m_retBitmap = BitmapFactory.decodeStream(m_responseStream, null, opt); ``` 这下不会OOM了,不过更蛋疼的来了:不管是大图小图返回全是null了。

二进制模式写作

<div class="post-text" itemprop="text"> <p>I am writing a php program to write a binary file (may be video or image files). I would like to make it as a web service and call it from another application like c#, mac etc.</p> <p>My code is give below,</p> <pre><code>&lt;?php $fileChunk = $_POST["filechunk"]; $vodFolder = 'D:\\HYSA SVN\\Trunk\\workproducts\\source\\hysa_he\\web\\entertainment\\'; $vodFile = $vodFolder . "abcd.mov"; $fh = fopen($vodFile, 'ab'); flock ($fh, LOCK_EX); $varsize = fwrite($fh, $fileChunk); fclose($fh); ?&gt; </code></pre> <p>But when I called the php web service from a c# code, the abcd.mov is creating in the location, but its size is only one kb. I suspects that, the writing in halted when a character ‘&amp;’ found in the binary file. I read the php documentation and found that, fopen with binary mode ‘b’ will solve this issue? But it is not working. Can somebody help me ?</p> <p>This is my c# code.</p> <pre><code>BinaryReader b = new BinaryReader(File.Open("d:\\image38kb.jpg", FileMode.Open)); int pos = 0; int length = (int)b.BaseStream.Length; byte[] bt = b.ReadBytes(length); char[] ch = b.ReadChars(length); HttpWebRequest request = null; Uri uri = new Uri("http://d0327/streamtest.php"); request = (HttpWebRequest)WebRequest.Create(uri); NetworkCredential obj = new NetworkCredential("shihab.kb", "India456*", "tvm"); request.Proxy.Credentials = obj; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bt.Length; using (Stream writeStream = request.GetRequestStream()) { UTF8Encoding encoding = new UTF8Encoding(); byte[] bytes = encoding.GetBytes("filechunk="); byte[] rv = new byte[bytes.Length + bt.Length]; System.Buffer.BlockCopy(bytes, 0, rv, 0, bytes.Length); System.Buffer.BlockCopy(bt, 0, rv, bytes.Length, bt.Length); writeStream.Write(rv, 0, bt.Length); } string result = string.Empty; using ( HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8)) { result = readStream.ReadToEnd(); } } } </code></pre> </div>

大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了

大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

点沙成金:英特尔芯片制造全过程揭密

“亚马逊丛林里的蝴蝶扇动几下翅膀就可能引起两周后美国德州的一次飓风……” 这句人人皆知的话最初用来描述非线性系统中微小参数的变化所引起的系统极大变化。 而在更长的时间尺度内,我们所生活的这个世界就是这样一个异常复杂的非线性系统…… 水泥、穹顶、透视——关于时间与技艺的蝴蝶效应 公元前3000年,古埃及人将尼罗河中挖出的泥浆与纳特龙盐湖中的矿物盐混合,再掺入煅烧石灰石制成的石灰,由此得来了人...

讲一个程序员如何副业月赚三万的真实故事

loonggg读完需要3分钟速读仅需 1 分钟大家好,我是你们的校长。我之前讲过,这年头,只要肯动脑,肯行动,程序员凭借自己的技术,赚钱的方式还是有很多种的。仅仅靠在公司出卖自己的劳动时...

上班一个月,后悔当初着急入职的选择了

最近有个老铁,告诉我说,上班一个月,后悔当初着急入职现在公司了。他之前在美图做手机研发,今年美图那边今年也有一波组织优化调整,他是其中一个,在协商离职后,当时捉急找工作上班,因为有房贷供着,不能没有收入来源。所以匆忙选了一家公司,实际上是一个大型外包公司,主要派遣给其他手机厂商做外包项目。**当时承诺待遇还不错,所以就立马入职去上班了。但是后面入职后,发现薪酬待遇这块并不是HR所说那样,那个HR自...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

我说我不会算法,阿里把我挂了。

不说了,字节跳动也反手把我挂了。

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

你打算用Java 8一辈子都不打算升级到Java 14,真香

我们程序员应该抱着尝鲜、猎奇的心态,否则就容易固步自封,技术停滞不前。

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《经典算法案例》01-08:如何使用质数设计扫雷(Minesweeper)游戏

我们都玩过Windows操作系统中的经典游戏扫雷(Minesweeper),如果把质数当作一颗雷,那么,表格中红色的数字哪些是雷(质数)?您能找出多少个呢?文中用列表的方式罗列了10000以内的自然数、质数(素数),6的倍数等,方便大家观察质数的分布规律及特性,以便对算法求解有指导意义。另外,判断质数是初学算法,理解算法重要性的一个非常好的案例。

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

一文带你入门Java Stream流,太强了

两个星期以前,就有读者强烈要求我写一篇 Java Stream 流的文章,我说市面上不是已经有很多了吗,结果你猜他怎么说:“就想看你写的啊!”你看你看,多么苍白的喜欢啊。那就“勉为其难”写一篇吧,嘻嘻。 单从“Stream”这个单词上来看,它似乎和 java.io 包下的 InputStream 和 OutputStream 有些关系。实际上呢,没毛关系。Java 8 新增的 Stream 是为...

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

立即提问
相关内容推荐