thắc mắc [C#] Thắc mắc về gửi Http Request

  • Người tạo chủ đề Người tạo chủ đề Bluesphere
  • Ngày bắt đầu Ngày bắt đầu

Bluesphere

Senior Member
Các bác cứu em vụ này với ạ.
Em thì không phải là dân IT nhưng có mày mò tý C# để làm mấy tool nhỏ phục vụ công việc thôi.

Hiện tại thì em có nhu cầu lấy thông tin về doanh nghiệp từ trang masothue.com

Mình có mày mò thì biết được cách thức mà web đấy nó hoạt động như sau: khi nhập Mã số thuế vào khung tìm kiếm thì đầu tiên nó sẽ gửi request tới trang "https://masothue.com/Ajax/Token/" để lấy 1 dải Token, xong lại gửi tiếp 1 request tới trang "https://masothue.com/Ajax/Search/". Request này có Form Data dạng như sau:

q=6300177249&type=auto&token=O4fHVSQUMC&force-search=1

Trong đó thì 6300177249 là mã số thuế cần tra cứu, O4fHVSQUMC là token lấy từ bước trên. Các giá trị còn lại thì ko cần quan tâm.

Và response trả ra sẽ có dạng: {"success":1,"typeId":6,"type":"m\u00e3 s\u1ed1 thu\u1ebf","url":"\/6300177249-cong-ty-co-phan-thuong-mai-dau-tu-dau-khi-nam-song-hau","force-search":"1","numRows":1}

Và cái mình cần lấy là cái đoạn url

Mình có thử dùng HttpClient để gửi request nhưng chỉ lấy được đến bước lấy token, còn đến bước lấy url thì response lại trả ra dạng rỗng là {"success":1,"url":"\/"}

Không có thông tin về url mình cần.

Có bác nào có thể chỉ cho em biết cách làm không ạ. Em cảm ơn.
 
Vì đơn giản là phía máy chủ nó xác nhận thím gửi thiếu thông tin bên http request. Để lấy được thì thím phải đầy đủ, thím thử với cURL xem sao. Ví dụ cURL nó gửi http header như này:

JavaScript:
curl -v \
     -H 'Host: restapi.some-site.com' \
     -H 'Connection: keep-alive' \
     -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
     -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
     -e localhost \
     -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
     'http://restapi.some-site.com/getsomething?argument=value&argument2=value'
 
Vì đơn giản là phía máy chủ nó xác nhận thím gửi thiếu thông tin bên http request. Để lấy được thì thím phải đầy đủ, thím thử với cURL xem sao. Ví dụ cURL nó gửi http header như này:

JavaScript:
curl -v \
     -H 'Host: restapi.some-site.com' \
     -H 'Connection: keep-alive' \
     -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
     -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
     -e localhost \
     -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
     'http://restapi.some-site.com/getsomething?argument=value&argument2=value'
Cảm phiền thím có thể code mẫu cho em phát được ko ạ. Em toàn mày mò trên gg nên ko có căn bản :(
 
Cảm phiền thím có thể code mẫu cho em phát được ko ạ. Em toàn mày mò trên gg nên ko có căn bản :(
Nếu thím biết sơ sơ C# thì thử cái này xem. Cái này thì k cần cURL cho thím dễ dùng

C#:
using System.Net.Http;

var client = new HttpClient();

// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(new [] {
    new KeyValuePair<string, string>("text", "This is a block of text"),
});

// Get the response.
HttpResponseMessage response = await client.PostAsync(
    "http://api.repustate.com/v2/demokey/score.json",
    requestContent);

// Get the response content.
HttpContent responseContent = response.Content;

// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
    // Write the output.
    Console.WriteLine(await reader.ReadToEndAsync());
}
 
Nếu thím biết sơ sơ C# thì thử cái này xem. Cái này thì k cần cURL cho thím dễ dùng

C#:
using System.Net.Http;

var client = new HttpClient();

// Create the HttpContent for the form to be posted.
var requestContent = new FormUrlEncodedContent(new [] {
    new KeyValuePair<string, string>("text", "This is a block of text"),
});

// Get the response.
HttpResponseMessage response = await client.PostAsync(
    "http://api.repustate.com/v2/demokey/score.json",
    requestContent);

// Get the response content.
HttpContent responseContent = response.Content;

// Get the stream of the content.
using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
{
    // Write the output.
    Console.WriteLine(await reader.ReadToEndAsync());
}
Cái code này mà muốn thêm mấy cái Header như kiểu User Agent, Content Type các thứ thì như nào vậy thím.
 
Các bác cứu em vụ này với ạ.
Em thì không phải là dân IT nhưng có mày mò tý C# để làm mấy tool nhỏ phục vụ công việc thôi.

Hiện tại thì em có nhu cầu lấy thông tin về doanh nghiệp từ trang masothue.com

Mình có mày mò thì biết được cách thức mà web đấy nó hoạt động như sau: khi nhập Mã số thuế vào khung tìm kiếm thì đầu tiên nó sẽ gửi request tới trang "https://masothue.com/Ajax/Token/" để lấy 1 dải Token, xong lại gửi tiếp 1 request tới trang "https://masothue.com/Ajax/Search/". Request này có Form Data dạng như sau:

q=6300177249&type=auto&token=O4fHVSQUMC&force-search=1

Trong đó thì 6300177249 là mã số thuế cần tra cứu, O4fHVSQUMC là token lấy từ bước trên. Các giá trị còn lại thì ko cần quan tâm.

Và response trả ra sẽ có dạng: {"success":1,"typeId":6,"type":"m\u00e3 s\u1ed1 thu\u1ebf","url":"\/6300177249-cong-ty-co-phan-thuong-mai-dau-tu-dau-khi-nam-song-hau","force-search":"1","numRows":1}

Và cái mình cần lấy là cái đoạn url

Mình có thử dùng HttpClient để gửi request nhưng chỉ lấy được đến bước lấy token, còn đến bước lấy url thì response lại trả ra dạng rỗng là {"success":1,"url":"\/"}

Không có thông tin về url mình cần.

Có bác nào có thể chỉ cho em biết cách làm không ạ. Em cảm ơn.
Dùng python scrap web tiện hơn đó fen. Tui cũng mày mò :too_sad:

Đang scrap hscode về mà bị trang nó chặn IP hoài :too_sad:
 
Cái này nó liên quan đến session chứ không phải mỗi cái form token kia. Bạn nên học cho cẩn thận chứ cứ ăn xổi thì không ổn.
 
Thím copy đoạn curl rồi import vào postman xong click vào biểu tượng <> thì phải gần chỗ send request, chọn ngôn ngữ là là tự có code cho thím. Copy paste vào thôi không phải code :ROFLMAO::ROFLMAO::ROFLMAO:

Sent from vsmart Live via nextVOZ
 
Cái này nó liên quan đến session chứ không phải mỗi cái form token kia. Bạn nên học cho cẩn thận chứ cứ ăn xổi thì không ổn.
Trời ạ. Mình học sơ để code phục vụ công việc chính thôi chứ có cần kiếm tiền từ code đâu mà bác nặng lời thế.
 
Trời ạ. Mình học sơ để code phục vụ công việc chính thôi chứ có cần kiếm tiền từ code đâu mà bác nặng lời thế.
Bác pull data về cũng nên cẩn thận đọc điều khoản sử dụng của họ nhé.

Screenshot 2021-10-12 at 11.55.15 AM.png
 
Mã:
curl 'https://masothue.com/Ajax/Search' -X POST -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'X-Requested-With: XMLHttpRequest' -H 'Origin: https://masothue.com' -H 'Connection: keep-alive' -H 'Referer: https://masothue.com/' -H 'Cookie: PHPSESSID=8aqo42d31nhqlorrqpb2ufug6f' -H 'Sec-Fetch-Dest: empty' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Site: same-origin' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'TE: trailers' --data-raw 'q=6300177249&type=auto&token=OSftBapwEl&force-search=1'

{"success":1,"typeId":6,"type":"m\u00e3 s\u1ed1 thu\u1ebf","url":"\/6300177249-cong-ty-co-phan-thuong-mai-dau-tu-dau-khi-nam-song-hau","force-search":"1","numRows":1}
 
Mã:
curl 'https://masothue.com/Ajax/Search' -X POST -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:93.0) Gecko/20100101 Firefox/93.0' -H 'Accept: application/json, text/javascript, */*; q=0.01' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'X-Requested-With: XMLHttpRequest' -H 'Origin: https://masothue.com' -H 'Connection: keep-alive' -H 'Referer: https://masothue.com/' -H 'Cookie: PHPSESSID=8aqo42d31nhqlorrqpb2ufug6f' -H 'Sec-Fetch-Dest: empty' -H 'Sec-Fetch-Mode: cors' -H 'Sec-Fetch-Site: same-origin' -H 'Pragma: no-cache' -H 'Cache-Control: no-cache' -H 'TE: trailers' --data-raw 'q=6300177249&type=auto&token=OSftBapwEl&force-search=1'

{"success":1,"typeId":6,"type":"m\u00e3 s\u1ed1 thu\u1ebf","url":"\/6300177249-cong-ty-co-phan-thuong-mai-dau-tu-dau-khi-nam-song-hau","force-search":"1","numRows":1}
Mình có viết 2 cái method để thực hiện mà vẫn oẳng :(

C#:
private Tuple<string, string> GetToken()
        {
            var client = new RestClient("https://masothue.com/Ajax/Token");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36";
            request.AddHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            request.AddHeader("Accept-Language", "en-US,en;q=0.5");
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            request.AddHeader("X-Requested-With", "XMLHttpRequest");
            request.AddHeader("Origin", "https://masothue.com");
            request.AddHeader("Connection", "keep-alive");
            request.AddHeader("Referer", "https://masothue.com/");
            request.AddHeader("Sec-Fetch-Dest", "empty");
            request.AddHeader("Sec-Fetch-Mode", "cors");
            request.AddHeader("Sec-Fetch-Site", "same-origin");
            request.AddHeader("Pragma", "no-cache");
            request.AddHeader("Cache-Control", "no-cache");
            request.AddHeader("TE", "trailers");
            IRestResponse response = client.Execute(request);

            string content = response.Content;
            DTO.TokenResponse tokenResponse = JsonConvert.DeserializeObject<DTO.TokenResponse>(content);
            string Token = tokenResponse.token;
            string cookies = "";
            foreach (var c in response.Cookies)
            {
                if (c.Name.Contains("SESSID") == true)
                {
                    cookies = c.Name + "=" + c.Value.ToString();
                }
            }

            Tuple<string, string> result = new Tuple<string, string>(Token, cookies);

            return result;

        }

        private string GetResponse(string MaSoThue, Tuple<string,string> TokenCookies)
        {
            var client = new RestClient("https://masothue.com/Ajax/Search");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            client.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36";
            request.AddHeader("Accept", "application/json, text/javascript, */*; q=0.01");
            request.AddHeader("Accept-Language", "en-US,en;q=0.5");
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            request.AddHeader("X-Requested-With", "XMLHttpRequest");
            request.AddHeader("Origin", "https://masothue.com");
            request.AddHeader("Connection", "keep-alive");
            request.AddHeader("Referer", "https://masothue.com/");
            request.AddHeader("Cookie", TokenCookies.Item2);
            request.AddHeader("Sec-Fetch-Dest", "empty");
            request.AddHeader("Sec-Fetch-Mode", "cors");
            request.AddHeader("Sec-Fetch-Site", "same-origin");
            request.AddHeader("Pragma", "no-cache");
            request.AddHeader("Cache-Control", "no-cache");
            request.AddHeader("TE", "trailers");
            string body = string.Format(@"q={0}&type=auto&token={1}&force-search=1", MaSoThue, TokenCookies.Item1);
            request.AddParameter("application/x-www-form-urlencoded; charset=UTF-8", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            string result = response.Content;

            return result;
        }

Khi gọi lần lượt 2 cái hàm này thì response trả ra vẫn là: {"success":1,"url":"\/"} huhu :(
 
C#:
        public static HttpClient _httpClient;
        static void Main(string[] args)
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol =
            SecurityProtocolType.Tls
            | SecurityProtocolType.Tls11
            | SecurityProtocolType.Tls12
            | SecurityProtocolType.Ssl3;
            ServicePointManager
            .ServerCertificateValidationCallback +=
            (sender, cert, chain, sslPolicyErrors) => true;

            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
            _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36");
            string token = GetToken().GetAwaiter().GetResult();
            Console.WriteLine(token);

            string info = GetInfo(token).GetAwaiter().GetResult();
            Console.WriteLine(info);
            Console.ReadLine();
        }
        private static async Task<string> GetToken()
        {
            string urlGetToken = "https://masothue.com/Ajax/Token";
            var payload = new FormUrlEncodedContent(new []
            {
                new KeyValuePair<string, string>("r", "i4lkt8")
            }) ;
            var request = await _httpClient.PostAsync(urlGetToken, payload);
            var responseContent = await request.Content.ReadAsStringAsync();
            dynamic parseData = JsonConvert.DeserializeObject<dynamic>(responseContent);
            string token = Convert.ToString(parseData.token);
            return token;
        }
        private static async Task<string> GetInfo(string token)
        {
            string urlGetToken = "https://masothue.com/Ajax/Search";
            var payload = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("q", "6300177249"),
                new KeyValuePair<string, string>("type", "auto"),
                new KeyValuePair<string, string>("token", token),
                new KeyValuePair<string, string>("force-search", "1")

            });
            var request = await _httpClient.PostAsync(urlGetToken, payload);
            var responseContent = await request.Content.ReadAsStringAsync();
            return responseContent;
        }

Đây nhé thím, em test rồi, thím tự xử lý tiếp các khúc sau nhé
 
Dùng python scrap web tiện hơn đó fen. Tui cũng mày mò :too_sad:

Đang scrap hscode về mà bị trang nó chặn IP hoài :too_sad:
Mình cũng gặp lỗi tương tự bác, mình có cào 1 trang web TMĐT bị chặn IP hoài, mình pass bằng cách lấy proxy free trên mạng (https://free-proxy-list.net/...), rồi đăng nhập vào web cần cào bằng proxy mới lấy được này xong mới cào, mỗi lần load page mới là lấy 1 proxy mới, cào vài trăm trang ngon lành luôn :D
 

Thống kê chủ đề

Ngày tạo
Bluesphere,
Người trả lời cuối
lon_ton_sai_vat,
Trả lời
20
Lượt xem
4.198
Quay lại
Lên đầu trang