java - 带有请求 header 的 Web 客户端

标签 java .net sockets httpclient webclient

我在.net中的代码如下。我想用java写。我该怎么做?我应该使用 httpclient 还是套接字来执行此操作?

           using (WebClient wc = new WebClient())
            {
                wc.Encoding = System.Text.Encoding.UTF8;
                wc.Headers.Add("HOST", "example.com");
                wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0"); 
                wc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                wc.Headers.Add("Accept-Language", "tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3");
                html = wc.DownloadString(link);
                if (temp == null)
                    return string.Empty;

                return html;
             }

最佳答案

使用 HttpUrlConnection,因为它带有默认的 JDK。无需下载额外的库。 这是上面这段代码的java翻译

public static String get(String link){
   HttpURLConnection connection=null;
   try{  
      URL url=new URL(link);
      connection=(HttpURLConnection)url.openConnection();
      connection.setRequestMethod("GET");
      connection.setRequestProperty("HOST", "example.com");
      connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0");
      connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
      connection.setRequestProperty("Accept-Language", "tr-TR,tr;q=0.8,en-US;q=0.5,en;q=0.3");
      connection.setDoInput(true);
      connection.setDoOutput(true);
      BufferedReader in=new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
      String line,response="";
      while((line=in.readLine())!=null)
         response+=(line+"\n");
      in.close();
      return response;
   }catch(Exception e){}
   return "";
}

关于java - 带有请求 header 的 Web 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13614289/

相关文章:

java - 如何从这个 JSON 对象中获取艺术家姓名的值?

java - 后退按钮在模拟器上工作,但在 Android 设备上不起作用

Java JList 在使用 KeyListener 时报告不正确的索引

c# - MVVM 疯狂 : Commands

c++ - poll() socket编程tcp linux多连接问题

java - 编译错误:Exception is never thrown in body of corresponding try statement

c# - 如何为 Wcf 服务创建 Asmx 客户端

python-3.x - 为什么不能将多个客户端同时连接到服务器? Python

Java多客户端服务器程序

c# - 在 ASP.NET Framework 3.5 中从 url 隐藏 .aspx