Setting the HTTP User-agent in Java

Just testing the newly installed iG:Syntax Hiliter Plugin while trying not to post something completely useless ;)

JAVA5:
  1. String userAgent = "my-user-agent/1.0";
  2. URL url = new URL("http://www.example.com/"); // would have to handle MalformedURLException
  3. URLConnection connection = null;
  4. InputStream is = null;
  5. try {
  6.   connection = url.openConnection();
  7.   // here's the essential line:
  8.   connection.addRequestProperty("User-Agent", userAgent);
  9.   is = connection.getInputStream();
  10.   // ...do something with that input stream...
  11. } catch (IOException e) {
  12.   LOG.error("Error reading " + url, e);
  13. } finally {
  14.   if (is != null) {
  15.     try {
  16.       is.close();
  17.     } catch (IOException e) {
  18.       if (LOG.isWarnEnabled()) {
  19.         LOG.warn("Error closing input stream: " + url, e);
  20.       }
  21.     } // catch
  22.   } // if
  23. } // finally

Einen Kommentar schreiben

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>