【问题标题】:Web client with request headers带有请求标头的 Web 客户端
【发布时间】:2012-11-28 20:58:55
【问题描述】:

我在 .net 中的代码如下所示。我想用java写它。我该怎么做?我应该使用 httpclient 还是 socket 来做到这一点?

           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;
             }

【问题讨论】:

  • 你会发现 HttpClient 更容易使用。

标签: java .net sockets httpclient webclient


【解决方案1】:

使用默认 JDK 附带的 HttpUrlConnection。无需下载额外的库。 这是上面这段代码在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 "";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    相关资源
    最近更新 更多