📄 resourceutility.java
字号:
package com.itpath.examples.voter.util;
import com.itpath.examples.voter.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import java.util.*;
public class ResourceUtility
{
private static String RESOURCE_URL = VoterMidlet.RESOURCE_URL;
private static String LOAD_URL = RESOURCE_URL;
private static String QUESTION = "?";
public static VoteSummary getVoteSummary()
{
String xml = loadVoteResults();
System.out.println(xml);
return convertXMLToVoteSummary( xml);
}
private static VoteSummary convertXMLToVoteSummary(String xml)
{
InputStreamReader insr = new InputStreamReader( new ByteArrayInputStream(xml.getBytes() ) );
VoteSummary voteSummary = null;
try
{
voteSummary = XMLUtil.getVoteResults(insr);
} catch (IOException ioe)
{}
return voteSummary;
}
public static VoteSummary addEntry(Vote vote)
{
StringBuffer requestString = new StringBuffer();
requestString.append(QUESTION + vote.toRequestString() );
String xml = backendComms(LOAD_URL, requestString.toString() );
return convertXMLToVoteSummary(xml);
}
public static String loadVoteResults()
{
return backendComms(LOAD_URL, "");
}
public static String backendComms(String requestURL, String requeststring)
{
HttpConnection hc = null;
DataInputStream dis = null;
StringBuffer messagebuffer = new StringBuffer();
String requestString = requestURL + requeststring;
try
{
// Open up a http connection with the Web server
// for both send and receive operations
hc = (HttpConnection) Connector.open(requestString, Connector.READ_WRITE);
// Set the request method to GET
hc.setRequestMethod(HttpConnection.GET);
// Retrieve the response back from the servlet
dis = new DataInputStream(hc.openInputStream());
int ch;
// Check the Content-Length first
long len = hc.getLength();
if(len!=-1)
{
byte [] bytebuffer = new byte[(int)len];
for(int i = 0;i<len;i++)
{
if((ch = dis.read())!= -1)
{
bytebuffer[i] = (byte)ch;
}
}
messagebuffer.append(
new String(bytebuffer) );
} else {
// if the content-length is not available
while ((ch = dis.read()) != -1)
{
messagebuffer.append((char) ch);
}
}
dis.close();
} catch (IOException ioe) {
messagebuffer = new StringBuffer("ERROR!");
} catch (Exception e){
e.printStackTrace();
} finally {
// Free up i/o streams and http connection
try {
if (hc != null) hc.close();
} catch (IOException ignored) {}
try {
if (dis != null) dis.close();
} catch (IOException ignored) {}
}
return messagebuffer.toString();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -