Send client request and Get server response : Networks « J2ME « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » J2ME » NetworksScreenshots 
Send client request and Get server response
Send client request and Get server response

/*--------------------------------------------------
* ViewFile.java
*
* Send client request (method, header, body)
* Get server response (status, header, body)
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.com
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;

public class ViewFile extends MIDlet
{
  private String url = "http://www.corej2me.com/midpbook_v1e1/ch14/getHeaderInfo.txt";

  public void startApp()
  {
    try
    {
      processRequest();
    }
    catch (Exception e)
    {
      System.err.println("Msg: " + e.toString());
    }
  }    

  private void processRequest() throws IOException
  {
    HttpConnection http = null;
    InputStream iStrm = null;
    
    try
    {
      // Create the connection
      http = (HttpConnectionConnector.open(url);
      
      //----------------
      // Client Request
      //----------------
      // 1) Send request method
      http.setRequestMethod(HttpConnection.GET);
      
      // 2) Send header information (this header is optional)
      http.setRequestProperty("User-Agent""Profile/MIDP-1.0 Configuration/CLDC-1.0");
//      http.setRequestProperty("If-Modified-Since", "Mon, 16 Jul 2001 22:54:26 GMT");

      // If you experience IO problems, try 
      // removing the comment from the following line
      //http.setRequestProperty("Connection", "close");      
      
      // 3) Send body/data - No data for this request
      

      //----------------
      // Server Response
      //----------------
      System.out.println("url: " + url);
      System.out.println("-------------------------");      
      
      // 1) Get status Line
      System.out.println("Msg: " + http.getResponseMessage());                  
      System.out.println("Code: " + http.getResponseCode());                
      
      // 2) Get header information 
      if (http.getResponseCode() == HttpConnection.HTTP_OK)
      {
        System.out.println("field 0: " + http.getHeaderField(0));        
        System.out.println("field 1: " + http.getHeaderField(1));
        System.out.println("field 2: " + http.getHeaderField(2));        
        System.out.println("-------------------------");
                
        System.out.println("key 0: " + http.getHeaderFieldKey(0));        
        System.out.println("key 1 : " + http.getHeaderFieldKey(1));        
        System.out.println("key 2: " + http.getHeaderFieldKey(2));                
        System.out.println("-------------------------");
                                   
        System.out.println("content: " + http.getHeaderField("content-type"));
        System.out.println("date: " + http.getHeaderField("date"));
        System.out.println("last-modified: " + http.getHeaderField("last-modified"));                
        
        System.out.println("-------------------------");

        // 3) Get data (show the file contents)
        String str;
        iStrm = http.openInputStream();
        int length = (inthttp.getLength();
        if (length != -1)
        {
          // Read data in one chunk
          byte serverData[] new byte[length];
          iStrm.read(serverData);
          str = new String(serverData);
        }
        else  // Length not available...
        {
          ByteArrayOutputStream bStrm = new ByteArrayOutputStream();       
          
          // Read data one character at a time
          int ch;
          while ((ch = iStrm.read()) != -1)
            bStrm.write(ch);
  
          str = new String(bStrm.toByteArray());
          bStrm.close();                
        }
        
        System.out.println("File Contents: " + str);
        
        //-----------------------------
        // Show connection information
        //-----------------------------
        System.out.println("Host: " + http.getHost());
        System.out.println("Port: " + http.getPort());
        System.out.println("Type: " + http.getType());                
        
//        System.out.println("File: " + http.getFile());                        
//        System.out.println("Protocol: " + http.getProtocol());                        
//        System.out.println("URL: " + http.getURL());                                        
//        System.out.println("Query: " + http.getQuery());                                
      }
    }catch(Exception e){
       e.printStackTrace();
    
    }finally{
      // Clean up
      if (iStrm != null)
        iStrm.close();
      if (http != null)
        http.close();
    }
  }

  public void pauseApp(){}

  public void destroyApp(boolean unconditional){ }
}


           
       
Related examples in the same category
1. MIDlet to invoke a CGI script.
2. MIDlet to invoke a CGI script (POST method is used)
3. Https MIDlet
4. Pass a cookie (stored in rms) between the MIDlet and a Java servlet.
5. Use GET or POST to communicate with a Java servlet.
6. Use Java servlets sessions to tally golf scores.
7. Http Test
8. An example MIDlet to invoke a CGI script.An example MIDlet to invoke a CGI script.
9. Timer ServerTimer Server
10. Http ExampleHttp Example
11. Socket connectionSocket connection
12. Http ConnectionHttp Connection
13. Cookie MIDletCookie MIDlet
14. JargoneerJargoneer
15. Post MIDlet
16. Patchy MIDletPatchy MIDlet
17. MIDlet to invoke a CGI script (GET method).MIDlet to invoke a CGI script (GET method).
18. Fetch Page MidletFetch Page Midlet
19. Invoke Servlet Midlet 2
20. Invoke Servlet Midlet 1
21. MIDlet to invoke a CGI script (POST method is used) (2)MIDlet to invoke a CGI script (POST method is used) (2)
22. Demonstrates the functionality of DatagramConnection framework.Demonstrates the functionality of DatagramConnection framework.
23. Sample to demonstrate Http GET and POST from MIDlet
24. Get file from networkGet file from network
25. Midlet Servlet 2Midlet Servlet 2
26. MIDlet to fetch a page using an HttpConnectionMIDlet to fetch a page using an HttpConnection
27. A simple network clientA simple network client
28. Socket MIDletSocket MIDlet
29. www.amazon.com Book Ranking MIDletwww.amazon.com Book Ranking MIDlet
30. Time Server
31. Http MIDletHttp MIDlet
32. DatagramSenderDatagramSender
33. Datagram Receiver
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.