Java 的用户代理如何在 c# 中工作

本文关键字:工作 用户代理 Java | 更新日期: 2023-09-27 18:35:11

这是用于使用任何浏览器打开链接的 Java 代码。

    URL url = new URL(s);
    URLConnection spoof = url.openConnection();
    spoof.addRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X                       10_6_8) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30'"");
    BufferedReader in = new BufferedReader(new InputStreamReader(spoof.getInputStream()));
    String strline = "";
    String finalhtml = "";
    while((strline = in.readLine() ) != null){
        finalhtml = finalhtml + strline;
        System.out.println(finalhtml);
    }

用户代理如何在 c# 中工作 我读了几个答案,但没有明确提到?

Java 的用户代理如何在 c# 中工作

用户代理不是 C# 或 Java 的东西。它是一个字符串,与 Web 请求一起发送,用于标识原始请求者的机器、操作系统和浏览器。这是一个Web标准的东西,而不是编程的东西。

如果你试图将Java代码复制到C#中,你可能正在寻找的是HttpWebRequest和HttpWebResponse类。可以使用 UserAgent 属性设置 HttpWebRequest 的用户代理。

您的 Java 代码在 C# 中将如下所示:

using System;
using System.Net;
using System.IO;
using System.Text;
public class Program
{
    public static void Main()
    {
        string data = "";
        string s = "http://www.example.com";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(s);
        request.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X                       10_6_8) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30'"";
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {               
            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (Stream receiveStream = response.GetResponseStream()) 
                {
                    using (StreamReader readStream = new StreamReader(receiveStream))
                    {                       
                        data = readStream.ReadToEnd();
                    }
                }
            }
        }
        Console.WriteLine(data);
    }
}
// Create a new 'HttpWebRequest' object to the mentioned URL.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("https://www.yellowpages.com.au/search/listings?clue=Doctors&locationClue=Sydney%2C+NSW+2000&lat=&lon=");
myHttpWebRequest.UserAgent = ".NET Framework Test Client";
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse'variable.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
        // Display the contents of the page to the console.
Stream streamResponse = myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
Char[] readBuff = new Char[256];
int count = streamRead.Read(readBuff, 0, 256);
Console.WriteLine("'nThe contents of HTML Page are :'n");
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}
// Release the response object resources.
streamRead.Close();
streamResponse.Close();
myHttpWebResponse.Close();