BlackBerry Forums Support Community               

Closed Thread
 
LinkBack Thread Tools
Old 03-16-2010, 05:34 AM   #1 (permalink)
New Member
 
Join Date: Mar 2010
Model: 7100t
PIN: N/A
Carrier: dnt no
Posts: 5
Post Thanks: 0
Thanked 0 Times in 0 Posts
Default Internet Connecton and File Input

Please Login to Remove!

Hi guys I have a two part roblem here. I have been working on the http sample to retrive an xml file as a string of text. Unfortunately due to it's limitations and complication I decided I would have to start my app from scratch.

So first I need to download an xml file(doesn't matter if it is temp) and then I need to ocnvert the xml file to a string of text.

The xml location will always be the same url, and I will format the string from it's raw format so I don't need nodes, just convert the file to a string.

Please help, and thanks in advance.
Offline  
Old 03-16-2010, 10:54 AM   #2 (permalink)
Knows Where the Search Button Is
 
Join Date: Mar 2010
Model: N/A
PIN: N/A
Carrier: Fledge
Posts: 43
Post Thanks: 0
Thanked 0 Times in 0 Posts
Default

An XML file is no different than a standard text file, it is just structured differently, so no conversion is necessary. So all you need to do is make an HTTP request and save the response to a string?

See the sample here: Chapter 7: Hello Out There! Making a Network-Enabled Application - BeginningBlackBerry
Offline  
Old 03-16-2010, 11:56 AM   #3 (permalink)
New Member
 
Join Date: Mar 2010
Model: 7100t
PIN: N/A
Carrier: dnt no
Posts: 5
Post Thanks: 0
Thanked 0 Times in 0 Posts
Default

ok thanks, but i cant understand with all that unnesisery code. I hope it's not too much to ask but what could i do to simple download a file from the internet and convert it into a string.
Offline  
Old 03-16-2010, 12:18 PM   #4 (permalink)
Knows Where the Search Button Is
 
Join Date: Mar 2010
Model: N/A
PIN: N/A
Carrier: Fledge
Posts: 43
Post Thanks: 0
Thanked 0 Times in 0 Posts
Default

Well ok, it's not that simple but I'll try anyway.

Import the following classes into your project:
Code:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.HttpsConnection;

import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.WLANInfo;

public class HttpRequestDispatcher extends Thread {
    private String url;
    private String method; // GET or POST
    private RequestsHttp requester;
    private byte[] postData;

    public HttpRequestDispatcher(String url, String method, RequestsHttp requester, byte[] postData) {
        this.url = url;
        this.method = method;
        this.requester = requester;
        this.postData = postData;
    }
    
    public HttpRequestDispatcher(String url, String method, RequestsHttp requester) {
        this.url = url;
        this.method = method;
        this.requester = requester;
    }

    private ServiceRecord getWAP2ServiceRecord() {
        ServiceBook sb = ServiceBook.getSB();
        ServiceRecord[] records = sb.getRecords();

        for (int i = 0; i < records.length; i++) {
            String cid = records[i].getCid().toLowerCase();
            String uid = records[i].getUid().toLowerCase();
            if (cid.indexOf("wptcp") != -1 && uid.indexOf("wifi") == -1
                    && uid.indexOf("mms") == -1) {
                return records[i];
            }
        }

        return null;
    }

    public void run() {
        try {
            String connectionParameters = "";
            // JDE 4.3 is required to get WLANInfo
            if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
                // Connected to a WiFi access point
                connectionParameters = ";interface=wifi";
            } else {
                int coverageStatus = CoverageInfo.getCoverageStatus();
                ServiceRecord record = getWAP2ServiceRecord();
                if (record != null
                        // In JDE 4.5 CoverageInfo changed the name of COVERAGE_CARRIER to COVERAGE_DIRECT
                        // The constant value for both is the same, '1', so you can use that to avoid any
                        // dependency on JDE 4.5
                        && (coverageStatus & 1) == 1) {
                    // Have network coverage and a WAP 2.0 service book record
                    connectionParameters = ";deviceside=true;ConnectionUID=" + record.getUid();
                } else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
                    // Have an MDS service book and network coverage
                    connectionParameters = ";deviceside=false";
                } else if ((coverageStatus & 1) == 1) {
                    // Have network coverage but no WAP 2.0 service book record
                    connectionParameters = ";deviceside=true";
                }
            }

            System.out.println("Connection Params: " + connectionParameters);
            
            HttpConnection connection = (HttpConnection) Connector.open(url + connectionParameters);
            
            connection.setRequestMethod(method);
            if (method.equals("POST") && postData != null) {
                connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
                OutputStream requestOutput = connection.openOutputStream();
                requestOutput.write(postData);
                requestOutput.close();
            }
            int responseCode = connection.getResponseCode();
            if (connection instanceof HttpsConnection) {
                HttpsConnection secureConnection = (HttpsConnection) connection;
                String issuer = secureConnection.getSecurityInfo()
                        .getServerCertificate().getIssuer();
                System.out.println("Secure Connection! Certificate issued by: " + issuer);
                    
                
            }
            // Really you should check for more than just HTTP_OK
            if (responseCode != HttpConnection.HTTP_OK) {
                requester.requestFailed("Unexpected response code: " + responseCode);
                connection.close();
                return;
            }


            String contentType = connection.getHeaderField("Content-type");
            System.out.println("Length: " + connection.getLength());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            InputStream responseData = connection.openInputStream();
            byte[] buffer = new byte[10000];
            int bytesRead = responseData.read(buffer);
            while (bytesRead > 0) {
                baos.write(buffer, 0, bytesRead);
                bytesRead = responseData.read(buffer);
            }
            baos.close();
            connection.close();

            requester.requestSucceeded(baos.toByteArray(), contentType);
        } catch (IOException ex) {
            requester.requestFailed(ex.toString());
        }
    }
}
and

Code:
interface RequestsHttp {
	public void requestSucceeded(byte[] result, String contentType);
	public void requestFailed(final String errorMessage);
}
Then, here is the application code.

Code:
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.container.MainScreen;

public class NetworkExample extends UiApplication implements RequestsHttp {
	private EditField resultField = new EditField();
	private HttpRequestDispatcher dispatcher = new HttpRequestDispatcher("http://www.google.com", "GET", this);
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		NetworkExample app = new NetworkExample();
		app.enterEventDispatcher();
	}
	
	public NetworkExample() {
		dispatcher.start();
		MainScreen screen = new MainScreen();
		screen.add(resultField);
		pushScreen(screen);
	}

	public void requestFailed(String errorMessage) {
		Dialog.alert("Request failed.");
	}

	public void requestSucceeded(final byte[] result, String contentType) {
		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				resultField.setText(new String(result));
			}
		});
	}
}
Offline  
Old 03-17-2010, 04:11 AM   #5 (permalink)
New Member
 
Join Date: Mar 2010
Model: 7100t
PIN: N/A
Carrier: dnt no
Posts: 5
Post Thanks: 0
Thanked 0 Times in 0 Posts
Default

Thank you so much, it works like a charm...

<3
Offline  




Copyright 2004-2016 BlackBerryForums.com.
The names RIM and BlackBerry are registered Trademarks of BlackBerry Inc.