Page 1 of 2 12 LastLast
Results 1 to 10 of 12

Thread: Neopets Programming with Java

  1. #1

    Joined
    Jan 2012
    Posts
    171
    Userbars
    2
    Thanks
    9
    Thanked
    31/9
    DL/UL
    1/0
    Mentioned
    57 times
    Time Online
    22h 48m
    Avg. Time Online
    N/A

    Neopets Programming with Java

    This is just a quick write up with some .java files to help you get started. Joe requested this from me a while ago and I've been slacking on putting it up.

    First things first, a few files that may be beneficial to you:

    Connection.java

    This is the 'wrapper' or what you would use to connect to neopets and interact.
    It's simple to use. Once you create a new instance its just neo.get("") and neo.post("", new String[][] { {}, {} });
    If you need to set a referer, you can do that manually. Otherwise, the referer is set to the last page. There are a few modifications in this that I added such as proxy support, support for the potential botcheck, etc.

    Code:
    package manager;
    import java.io.*;
    import java.net.*;
    import java.nio.charset.Charset;
    import java.util.*;
    import java.util.zip.*;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    import javax.imageio.stream.ImageInputStream;
    import javax.swing.JOptionPane;
    import java.io.BufferedInputStream;
    
    /**
     *
     * @author Kaden
     */
    public class Connection implements Serializable {
       static final long serialVersionUID = 1L;
    
       String domain;
    
    public String referer;
       Map<String,String> cookies;
    
       private boolean useProxy;
       private String proxyIP;
       private int proxyPort;
       static String rpUseragent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8";
       static String rpAcceptText = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
       static String rpAcceptPng = "image/jpeg,image/*;q=0.8,*/*;q=0.5";
       static String rpAcceptLanguage = "en-us,en;q=0.8";
       static String rpAcceptEncoding = "gzip, deflate";
       static String rpAcceptCharset = "ISO-8859-1,utf-8;q=0.7,*;q=0.3";
       static String rpKeepAlive = "300";
       static String rpConnection = "keep-alive";
       static String rpContentType = "application/x-www-form-urlencoded";
    
       public Connection(String domain, Map<String,String> cookies, String referer) {
          this.domain = domain;
          this.cookies = cookies;
          this.referer = referer;
       }
    
       public Connection(String domain, Map<String,String> cookies) {
          this(domain, cookies, null);
       }
    
       public Connection(String domain, String referer) {
          this(domain, new HashMap<String,String>(), referer);
       }
    
       public Connection(String domain) {
          this(domain, new HashMap<String,String>(), null);
       }
    
       public String get(String url) {
          if(url.charAt(0) == '/')
             url = domain + url;
    
          try {
        	 HttpURLConnection conn;
        	 String strHTML = "";
        	 if (useProxy) {
        		 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIP, proxyPort));
        		 conn = (HttpURLConnection)(new URL(url.replaceAll(" ", "%20")).openConnection(proxy));
        	 } else {
        		 conn = (HttpURLConnection)(new URL(url.replaceAll(" ", "%20")).openConnection());
        	 }
             setRequestProperties(conn);
             conn.setRequestMethod("GET");
             referer = url;
             strHTML = read(conn);
             if (url.contains("neopets")) {
            	 if (strHTML.contains("hdrimg.php?srvfile")) {
            		 conn = (HttpURLConnection)(new URL(Functions.getBetween(strHTML, "hdrimg.php?srvfile=", (char)34 + "")).openConnection());
            		 setRequestProperties(conn);
                     conn.setRequestMethod("GET");
                     read(conn);
            	 } else if (strHTML.contains("npaward.php")) {
            		 conn = (HttpURLConnection)(new URL("http://www.neopets.com/npaward.php?r=" + Functions.getBetween(strHTML, "http://www.neopets.com/npaward.php?r=", (char)34 + "")).openConnection());
            		 setRequestProperties(conn);
                     conn.setRequestMethod("GET");
                     read(conn);
            	 }
             }
             return strHTML;
          } catch(IOException e1) {
             return null;
          }
       }
    
       public String post(String url, String[][] data) {
          if(url.charAt(0) == '/')
             url = domain + url;
    
          try {
        	 HttpURLConnection conn;
        	 String strHTML = "";
        	 if (useProxy) {
        		 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIP, proxyPort));
        		 conn = (HttpURLConnection)(new URL(url.replaceAll(" ", "%20")).openConnection(proxy));
        	 } else {
        		 conn = (HttpURLConnection)(new URL(url.replaceAll(" ", "%20")).openConnection());
        	 }
             setRequestProperties(conn);
             conn.setRequestMethod("POST");
             conn.setDoOutput(true);
    
             StringBuilder sb = new StringBuilder();
    
             for(int i = 0; i < data[0].length; i++)
                sb.append(URLEncoder.encode(data[0][i], "UTF-8")).append('=').append(URLEncoder.encode(data[1][i], "UTF-8")).append('&');
    
             conn.setRequestProperty("Content-Type", rpContentType);
             conn.setRequestProperty("Content-Length", Integer.toString(sb.length()-1));
    
             PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())));
             out.write(sb.substring(0, sb.length()-1));
             out.close();
    
             referer = url;
             strHTML = read(conn);
             if (url.contains("neopets")) {
            	 if (strHTML.contains("hdrimg.php?srvfile")) {
            		 conn = (HttpURLConnection)(new URL(Functions.getBetween(strHTML, "hdrimg.php?srvfile=", (char)34 + "")).openConnection());
            		 setRequestProperties(conn);
                     conn.setRequestMethod("GET");
                     read(conn);
            	 } else if (strHTML.contains("npaward.php")) {
            		 conn = (HttpURLConnection)(new URL("http://www.neopets.com/npaward.php?r=" + Functions.getBetween(strHTML, "http://www.neopets.com/npaward.php?r=", (char)34 + "")).openConnection());
            		 setRequestProperties(conn);
                     conn.setRequestMethod("GET");
                     read(conn);
            	 }
             }
             return strHTML;
          } catch(IOException e1) {
             return null;
          }
       }
       
    
       public BufferedImage getImageFromUrl(String url) {
    	   String imgURL = url; 
    	   URL url1 = null;
    	   try {
    		   url1 = new URL(imgURL);
    		   HttpURLConnection conn = (HttpURLConnection)(url1).openConnection();
    		   if(cookies != null && cookies.size() != 0)
    		         conn.setRequestProperty("Cookie", getCookieString());
    		   conn.connect();
    		   InputStream in = conn.getInputStream();
    		   Image image = null;
    		   image = ImageIO.read(in);
    		   BufferedImage cpimg=bufferImage(image); 
    		   return cpimg;
    	   } catch (Exception e) {
    		   return new BufferedImage(1, 1, 1); 
    	   }
       }  
       public BufferedImage bufferImage(Image image) { 
    	   return bufferImage(image,BufferedImage.TYPE_INT_RGB); 
       }	
       public BufferedImage bufferImage(Image image, int type) { 
    	   BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), type); 
    	   Graphics2D g = bufferedImage.createGraphics(); 
    	   g.drawImage(image, null, null); 
    	   return bufferedImage; 
       } 
    
       public boolean hasCookie(String key) {
          return cookies.containsKey(key);
       }
    
       public String getCookieString() {
          StringBuilder sb = new StringBuilder();
    
          for(String s : cookies.keySet())
             sb.append(s).append('=').append(cookies.get(s)).append(';');
    
          return sb.toString();
       }
       
       public boolean useProxy(boolean use, String ip, int port) {
    	   useProxy = use;
    	   proxyIP = ip;
    	   proxyPort = port;
    	   return use;
       }
    
       private void setRequestProperties(HttpURLConnection conn) {
          conn.setInstanceFollowRedirects(false);
          conn.setRequestProperty("User-Agent", rpUseragent);
          conn.setRequestProperty("Accept", rpAcceptText);
          conn.setRequestProperty("Accept-Language", rpAcceptLanguage);
          conn.setRequestProperty("Accept-Encoding", rpAcceptEncoding);
          conn.setRequestProperty("Accept-Charset", rpAcceptCharset);
          conn.setRequestProperty("Keep-Alive", rpKeepAlive);
          conn.setRequestProperty("Connection", rpConnection);
    
          if(referer != null && referer.length() != 0)
             conn.setRequestProperty("Referer", referer);
    
          if(cookies != null && cookies.size() != 0)
             conn.setRequestProperty("Cookie", getCookieString());
       }
       
       private void setRequestProperties2(HttpURLConnection conn) {
    	      conn.setInstanceFollowRedirects(false);
    	      conn.setRequestProperty("User-Agent", rpUseragent);
    	      conn.setRequestProperty("Accept", rpAcceptText);
    	      conn.setRequestProperty("Accept-Language", rpAcceptLanguage);
    	      conn.setRequestProperty("Accept-Encoding", rpAcceptEncoding);
    	      conn.setRequestProperty("Accept-Charset", "utf-8");
    	      conn.setRequestProperty("Connection", rpConnection);
    	      conn.setRequestProperty("Cache-Control", "max-age=0");
    
    
    	      if(cookies != null && cookies.size() != 0)
    	         conn.setRequestProperty("Cookie", getCookieString());
    	   }
    
       private String read(HttpURLConnection conn) throws IOException {
          BufferedReader in = null;
    
          if(conn.getContentEncoding() == null)
             in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          else
             if(conn.getContentEncoding().equalsIgnoreCase("gzip"))
                in = new BufferedReader(new InputStreamReader(new GZIPInputStream(conn.getInputStream())));
             else if(conn.getContentEncoding().equalsIgnoreCase("deflate"))
                in = new BufferedReader(new InputStreamReader(new InflaterInputStream(conn.getInputStream(), new Inflater(true))));
    
          
          StringBuilder sb = new StringBuilder();
          String s;
    
          while((s = in.readLine()) != null)
             sb.append(s).append('\n');
    
          putCookies(conn.getHeaderFields().get("Set-Cookie"));
          return conn.getHeaderFields() + sb.toString();
       }
    
       private void putCookies(List<String> cookieList) {
          if(cookieList == null)
             return;
    
          int index;
    
          for(String cookie : cookieList)
             cookies.put(cookie.substring(0, index = cookie.indexOf('=')), cookie.substring(index+1, cookie.indexOf(';', index)));
       }
       
       public void clearCookies() {
    	   cookies.clear();
       }
    }
    Functions.java

    I've included some basic functions such as getStringBetween, load file, etc.
    Code:
    package manager;
    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.StringSelection;
    import java.io.*;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    import javax.swing.JOptionPane;
    import javax.swing.table.DefaultTableModel;
    
    import userInterface.BotGUI;
    
    
    public class Functions {
    	
    	static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    	static Random rnd = new Random();
    
    	public static String randomString( int len ) 
    	{
    	   StringBuilder sb = new StringBuilder( len );
    	   for( int i = 0; i < len; i++ ) 
    	      sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
    	   return sb.toString();
    	}
       
        public static void copyStringToClipboard(String str) {
      	  StringSelection stringSelection = new StringSelection(str);
      	  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
      	  clipboard.setContents(stringSelection, null);
        }
        
        public static final int NOT_FOUND_INDEX = -1;
        public static String getStringBetween(String theString, String start, String end) {
            if(theString == null || start == null || end == null) {
              return null;
            }
            int startIndex = theString.indexOf(start);
            if(startIndex != NOT_FOUND_INDEX) {
              int endIndex = theString.indexOf(end, startIndex + start.length());
              if(endIndex != NOT_FOUND_INDEX) {
                return theString.substring(startIndex + start.length(), endIndex);
              }
            }
            return null;
          }
          
        public static void wait (int n){
             long t0, t1;
             t0 =  System.currentTimeMillis();
             do{
                 t1 = System.currentTimeMillis();
             }
             while (t1 - t0 < n);
         }
         
        public static String[] loadFile(final String f) {
    		String thisLine;
    		final List<String> s = new ArrayList<String>();
    		BufferedReader br = null;
    		try {
    			br = new BufferedReader(new FileReader(f));
    			while ((thisLine = br.readLine()) != null)
    				s.add(thisLine.trim());
    		} catch (IOException ioe) {
    			System.err.println("Error reading file " + f);
    			throw new RuntimeException(ioe);
    		} finally {
    			if(br!=null) try {
    				br.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    		return s.toArray(new String[s.size()]);
    	}
        
        
        public static PrintStream getOutputPrintStream(){
    		PrintStream outStream = null;
    		while (outStream == null) {
    			File f = new File("Settings/Accounts.nbf");
    			try {
    				outStream = new PrintStream(f);
    			} catch (FileNotFoundException e) {
    				JOptionPane.showMessageDialog(null, "Unable to Save Accounts - Please try again.");
    			}
    		}
    		return outStream;
    	}
    
    }


    Apart from this, what joe really wanted was the gui creator for eclipse that I use.

    Currently, I am using google's WindowBuilder Pro. It's a simple eclipse add-on that allows for quick gui creation. There are some bugs that i've found with it but nothing major and it should work for whatever you want to make.

    Link:
    (you need an account to see links)


    That's all I'm going to post for now but if you have any other questions then feel free to ask.
    I love Sage. <3

  2. The Following 20 Users Say Thank You to Sean For This Useful Post:

    bbuilder (10-16-2017),Cody. (06-22-2012),davebold370 (07-12-2012),deathwish42 (06-09-2012),Demo (10-11-2012),Ghosts (08-27-2014),hissi (11-10-2014),j03 (06-04-2012),Joseph (11-07-2012),Miguel (06-04-2012),Mikey (06-29-2012),♥ Munna ♥ (02-13-2024),musemfire (08-16-2012),neofreak (07-18-2012),Netus (10-11-2012),npm (11-14-2012),runbikesurf (11-14-2012),Ryan~ (06-09-2012),Tom (06-07-2012),w_is_awesome (06-27-2012)

  3. #2
    Zachafer's Avatar
    Joined
    Dec 2011
    Posts
    1,235
    Userbars
    11
    Thanks
    769
    Thanked
    1,466/678
    DL/UL
    98/0
    Mentioned
    512 times
    Time Online
    24d 13h 9m
    Avg. Time Online
    8m
    I highly recommend this post to anyone wanting to learn Java programming or programming in general.

    Java is a cross-platform programming language meaning your programs can be ran on any operating system.

    @(you need an account to see links)

  4. The Following 2 Users Say Thank You to Zachafer For This Useful Post:

    Mikey (06-29-2012),Ryan~ (06-09-2012)

  5. #3

    Joined
    Apr 2012
    Posts
    579
    Thanks
    64
    Thanked
    90/65
    DL/UL
    6/0
    Mentioned
    68 times
    Time Online
    N/A
    Avg. Time Online
    N/A
    Quote Originally Posted by Zachafer View Post
    I highly recommend this post to anyone wanting to learn Java programming or programming in general.

    Java is a cross-platform programming language meaning your programs can be ran on any operating system.

    @(you need an account to see links)
    Ahh that's good so if I go back to my windows XP computer someday I can use them on there, awesome :*

  6. #4
    deathwish42's Avatar
    Joined
    Jun 2012
    Posts
    388
    Userbars
    2
    Thanks
    46
    Thanked
    45/39
    DL/UL
    50/0
    Mentioned
    45 times
    Time Online
    21d 6h 5m
    Avg. Time Online
    7m
    wow thats amazing nice job im currently trying to learn java on codecademy im stuck on it though so ya nice topic i will come back to this once i learn how to do some major coding

  7. #5

    Joined
    Jul 2012
    Posts
    51
    Userbars
    1
    Thanks
    4
    Thanked
    7/7
    DL/UL
    5/0
    Mentioned
    4 times
    Time Online
    N/A
    Avg. Time Online
    N/A
    Coolness. It's a little more advance than what I know of java right now. What are the portals you use to access different things throughout neopets and how would i find those portals myself so i don't have to ask over and over again. lol Thank you so much. I love learning new things about programing and more involved i become with internet programing the better.

  8. #6
    BEDDOEDv's Avatar
    Joined
    Jul 2012
    Posts
    664
    Userbars
    3
    Thanks
    182
    Thanked
    109/53
    DL/UL
    106/0
    Mentioned
    32 times
    Time Online
    7d 10h 26m
    Avg. Time Online
    2m
    im trying to learn about java, i find its slow though a times

  9. #7
    npm's Avatar
    Joined
    Dec 2011
    Posts
    813
    Userbars
    15
    Thanks
    735
    Thanked
    564/219
    DL/UL
    84/3
    Mentioned
    109 times
    Time Online
    83d 21h 28m
    Avg. Time Online
    28m
    I'm studying java at school and this will really help me. I hope someday I can do a simple program for neopets by myself without asking anything and this is a really good begining for me (you know trying to learn about all the functions used on this and that ). So thank you



    Code:
    404 Not Found.

  10. #8
    Jesusinn's Avatar
    Joined
    Jan 2012
    Posts
    603
    Userbars
    3
    Thanks
    130
    Thanked
    105/66
    DL/UL
    28/0
    Mentioned
    62 times
    Time Online
    3d 12h 16m
    Avg. Time Online
    1m
    I just learn java in the school too.
    but I noob compared with him u.u
    thanks so much for the tutorial :3

  11. #9

    Joined
    Aug 2013
    Posts
    6
    Userbars
    0
    Thanks
    0
    Thanked
    0/0
    DL/UL
    10/0
    Mentioned
    Never
    Time Online
    6h 25m
    Avg. Time Online
    N/A
    WB is a bit buggy, yes. In the sense that you drag and drop a window/widget/whatever (I forget the technical term WBPro uses) and it auto-places the code for you in your existing program in a place that isn't exactly organized (or as organized as you'd want it to be)... which means you may have to manually put it somewhere else, every single time you drop a window/widget onto the screen.

    There is always straight coding via AWT and SWING, which I prefer; but am recently taking to JavaFX as a means to create a more attractive GUI for potential users... and JavaFX is, to me, a bit ghetto in the sense that its still new- and yes- there are several known bugs.

    Couple on top of all this, any time plug-ins are being installed with eclipse; you may have some kind of unexpected or unwarranted behaviour (such as the well-known "R" or Resource bug commonplace with Google's ADT Plug-In for Android Developers)

    I feel that Java is kinda' wanting when it comes to GUI development ( lacking the sheer simplicity of VB ); though every language/platform seems to have its own advantages over others, and simply familiarizing yourself with every language/platform's nuances will indeed make the process a lot more comfortable, as you get used to experiencing these same nuances over time and can work around or fix them via personal experience, effortlessly. But that all comes with familiarity and practice.

  12. #10

    Joined
    Jan 2014
    Posts
    54
    Userbars
    1
    Thanks
    6
    Thanked
    8/8
    DL/UL
    24/0
    Mentioned
    10 times
    Time Online
    1d 23h 5m
    Avg. Time Online
    N/A
    is java the best program for np bots?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •