Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HttpUrlConnection is not working

 
enkhbat dash
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I copy and paste http://www.google.com/search?q=test in address bar, it works perfectly. But when I using HttpUrlConnection to connect it, it doesn't work. Here is my code.




When I copy and paste link to address bar, it's accessing web via get method right? And code uses get method, too. Any suggestion and help?
 
amit punekar
Ranch Hand
Posts: 544
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I think you should try using

instead of
.

Regards,
Amit
 
enkhbat dash
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for quick reply, but changing by that doesn't make difference.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The HttpURLConnection uses "Java [Version]" as the default user agent.

Since Google is incredibly smart, it blocks requests that come from a java program.

You need to set the user agent to "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)" or the like
 
enkhbat dash
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, can you share me valid agent names?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here...

 
enkhbat dash
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks again. It works. You helped me a lot.
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No problem.

If you want to be stylish, turn the static final variables above into an enum (better approach).
 
enkhbat dash
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, I'll keep in mind.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic