Results 1 to 10 of 12

Thread: Neopets Programming with Java

Threaded View

  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)

Posting Permissions

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