1. 程式人生 > >C# 模擬傳送請求到java後臺 java程式碼接收處理引數的問題

C# 模擬傳送請求到java後臺 java程式碼接收處理引數的問題

前段時間接到一個需求,對接一個C#寫的工具類,給我們的系統後臺上傳資料。

需求不難,很常見,於是為了方便。我就這樣寫了(java框架SSH):

C#模擬請求的程式碼

 public static void Main(string[] args)
        {
            String postData = fileToString("D:\\test\\json.txt");
            Console.WriteLine(postData);
            string url = "ip:埠/專案名/tensionGroution.do?method=uploadData&data=" + postData;
            Console.WriteLine("******************************************");
            if (postData != null)
                PostUrl(url, postData);

            Console.ReadKey();
        }

        public static string PostUrl(string url, string postData)
        {
            string result = "";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.KeepAlive = false;
            req.ProtocolVersion = HttpVersion.Version10;
            req.Method = "POST";

            req.Timeout = 80000;//設定請求超時時間,單位為毫秒

            req.ContentType = "application/json";

            byte[] data = Encoding.UTF8.GetBytes(postData);

            req.ContentLength = data.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);

                reqStream.Close();
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            Stream stream = resp.GetResponseStream();

            //獲取響應內容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Console.WriteLine(postData);
            return result;
        }

        public static string fileToString(String filePath)
        {
            if (!File.Exists(filePath))
            {
                Console.WriteLine("檔案不存在");
                return null;
            }

            string strData = "";
            try
            {
                string line;
                // 建立一個 StreamReader 的例項來讀取檔案 ,using 語句也能關閉 StreamReader
                using (System.IO.StreamReader sr = new System.IO.StreamReader(filePath, System.Text.Encoding.GetEncoding("gb2312")))
                {
                    // 從檔案讀取並顯示行,直到檔案的末尾
                    while ((line = sr.ReadLine()) != null)
                    {

                        //Console.WriteLine(line);
                        strData += line;
                    }
                }
            }
            catch (Exception e)
            {
                // 向用戶顯示出錯訊息
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
            return strData;
        }



    }

提供上傳路徑,並且攜帶引數(json格式),通過C#的HttpWebRequest物件模擬了http的post請求。請求正常傳送。

java後臺也接收到了,接受方式是很常見的 :    String data = request.getParameter("data");

ok完成部署,測試無誤。 但是用了一段時間後,問題來了

C#後臺居然報錯了

排查原因 原來是請求介面的引數惹的禍

當拼接的引數過長的 請求協議拒絕傳送,所以報了錯。

解決方案:

     在C#模擬請求的程式碼了發現這樣一個類,其實已將操作了引數。

Stream 這個物件其實已經將引數以流的形式寫入到請求中了,之前的操作並沒有用。

瞭解到了Stream的原理之後,那麼就改變了請求介面,不去攜帶引數,Stream物件去處理。

string url = "ip:埠/專案名/tensionGroution.do?method=uploadData";(修改後的介面)。

然後java後臺接受這個引數也要處理了,顯然就是讀流了。

String tradeInfos = "";
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(request.getInputStream(), "utf-8")); // 讀取引數流

		String nextLine = bufferedReader.readLine();
		while (nextLine != null) {
			System.out.println(request.getCharacterEncoding());
			tradeInfos += nextLine;
			nextLine = bufferedReader.readLine();
		}
		System.out.println(tradeInfos);

這樣,就順利的得到了C#工具上傳的資料的。

當然也有別的請求 和接受的方式,找一個最合適的才是最好的!!