HTTP响应代码:403从客户端向服务器发送URL地址时

时间:2012-04-07 05:02:07

标签: java url client-server httpresponse

我试着写一个客户端服务器程序,在我的程序中,每回合,客户端向服务器发送两个String,第一个是网址,第二个是关于用户的一些随机信息。但是url地址到达服务器,我得到这个例外:

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.google.com.hk/search?hl=en&source=hp&q=java&gbv=2
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245)
    at java.net.URL.openStream(URL.java:1009)
    at server.Server.processClient(Dom.java:124)
    at server.Server.run(Dom.java:90)
    at server.Server.main(Dom.java:155)
Java Result: 1

但我不知道为什么会收到禁止的回复。

客户端

              private static BufferedWriter toServer;
....

  public void progressUpdated(NavigatorProgressEvent npe) {



            Matcher matcher = pattern.matcher (npe.getUrl().toString());


            if (matcher.matches ())
                        {
                System.out.println(npe.getUrl());
                        toServer.println(npe.getUrl().toString());


                                }

服务器端

...
   url = new URL(fromClient.readLine());

...

1 个答案:

答案 0 :(得分:0)

也许您在标题请求中错过了“User-Agent”。

尝试添加此代码:

httpUrlConnection.setRequestProperty("User-Agent","MyUserAgentName");

如果您未指定用户代理名称,则Google不会回复。并尝试选择一个好的用户代理名称:D