(HttpConnection) Connector.open("http://www.google.com"); does not responding - java-me

HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
String request = serverUrl; // + "?loc=" + location.getLat() + "," + location.getLng() + "data=" + message.getString();
try {
c = (HttpConnection) Connector.open("http://www.google.com");
c.setRequestMethod(HttpConnection.GET); //default
is = c.openInputStream(); // transition to connected!
int ch = 0;
for (int ccnt = 0; ccnt < 150; ccnt++) { // get the title.
ch = is.read();
if (ch == -1) {
break;
}
sb.append((char) ch);
return sb.toString();
}
} catch (IOException x) {
x.printStackTrace();
} finally {
try {
is.close();
c.close();
} catch (IOException x) {
x.printStackTrace();
}
}
System.out.println(sb.toString());
return null;
in the above code -- this line
(HttpConnection) Connector.open("http://www.google.com");
does not respond. what can i do to resolve this?

try the following
HttpConnection c = null;
InputStream is = null;
StringBuffer sb = new StringBuffer();
String request = serverUrl; // + "?loc=" + location.getLat() + "," + location.getLng() + "data=" + message.getString();
try {
c = (HttpConnection) Connector.open("http://www.google.com");
c.setRequestMethod(HttpConnection.GET); //default
int status_code=c.getResponseCode();
if(status_code!=HttpConnection.HTTP_OK)
{
//Show the failure message to user
return;
}
//Remaining part is same as your code

In lots of phones, and some simulators, you can only open a connection in another thread. that is to say, if you try to connect in main therad = UI thread it wont work and wont tell you anything. Try simply wrapping your method in a new thread

Related

URLConnection dont work on linux

i have a big Problem at the moment and i hope anybody know a fix.
on my server i use this code to check vote counts on a website:
#Override
public int getVoteCount()
{
int votes = 0;
try
{
URL oracle = new URL(getLinkToCheck());
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.contains("<div class='list_8' style=\"font-weight: bold\">"))
{
String line = inputLine.split("<div class='list_8' style=\"font-weight: bold\">")[1].split("</div>")[0].trim().replaceAll(" ", "");
votes = Integer.parseInt(line);
if (VoteManager.VOTE_DEBUG)
{
System.out.println("VoteManager [" + getClass().getSimpleName() + "]: Votes count: [" + votes + "]");
}
return votes;
}
}
in.close();
}
catch (Exception e)
{
System.out.println(e);
}
return votes;
}

Command Timeout, longer to get response back

I am executing large query,so my app throwing time out error. Some of the thread suggested to added command time out but after adding those lines it take longer to get response back, any idea why or what am i missing in my code?
public int CreateRecord(string theCommand, DataSet theInputData)
{
int functionReturnValue = 0;
int retVal = 0;
SqlParameter objSqlParameter = default(SqlParameter);
DataSet dsParameter = new DataSet();
int i = 0;
try
{
//Set the command text (stored procedure name or SQL statement).
mobj_SqlCommand.CommandTimeout = 120;
mobj_SqlCommand.CommandText = theCommand;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
for (i = 0; i <= (theInputData.Tables.Count - 1); i++)
{
if (theInputData.Tables[i].Rows.Count > 0)
{
dsParameter.Tables.Add(theInputData.Tables[i].Copy());
}
}
objSqlParameter = new SqlParameter("#theXmlData", SqlDbType.Text);
objSqlParameter.Direction = ParameterDirection.Input;
objSqlParameter.Value = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + dsParameter.GetXml();
//Attach to the parameter to mobj_SqlCommand.
mobj_SqlCommand.Parameters.Add(objSqlParameter);
//Finally, execute the command.
retVal = (int)mobj_SqlCommand.ExecuteScalar();
//Detach the parameters from mobj_SqlCommand, so it can be used again.
mobj_SqlCommand.Parameters.Clear();
functionReturnValue = retVal;
}
catch (Exception ex)
{
throw new System.Exception(ex.Message);
}
finally
{
//Clean up the objects created in this object.
if (mobj_SqlConnection.State == ConnectionState.Open)
{
mobj_SqlConnection.Close();
mobj_SqlConnection.Dispose();
mobj_SqlConnection = null;
}
if ((mobj_SqlCommand != null))
{
mobj_SqlCommand.Dispose();
mobj_SqlCommand = null;
}
if ((mobj_SqlDataAdapter != null))
{
mobj_SqlDataAdapter.Dispose();
mobj_SqlDataAdapter = null;
}
if ((dsParameter != null))
{
dsParameter.Dispose();
dsParameter = null;
}
objSqlParameter = null;
}
return functionReturnValue;
}

Shoutcast radio with J2ME

I have my application playing the radio stream which is shoutcast streaming. I have searched on the internet for 2 days but my application stills can't play this url. I don't know how to solve this.
This is my sample source code.
String url1 = "http://203.150.224.142:8003/;
HttpConnection con= (HttpConnection)Connector.open(url1);
InputStream is = con.openInputStream();
player = Manager.createPlayer(is, "audio/mpeg");
player.realize();
player.prefetch();
player.start();
I have used this code in production, it should work for you also.
HttpConnection conn = (HttpConnection) Connector.open(music.getTrack_url() + "?streamable=true", Connector.READ_WRITE);
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
is = conn.openInputStream();
player = Manager.createPlayer(is, "audio/mp3");
player.addPlayerListener(thisObj);
player.realize();
player.prefetch();
player.start();
}
Try This.
public void loadShoutcast(String url)
{
StreamConnection connection = null;
int BUFFER_SIZE = 1024;
DataOutputStream dos_ = null;
OutputStream os_ = null;
try
{
System.out.println("opening connection " + url);
//Shoutcast URL
connection = (StreamConnection) Connector.open(url);
os_ = connection.openOutputStream();
dos_ = new DataOutputStream(os_);
// send the HTTP request
String req = "GET / HTTP/1.1\r\nUser-Agent: Profile/MIDP-1.0 Configuration/CLDC-1.0\r\n\r\n";
dos_.write(req.getBytes());
is = null;
is = connection.openInputStream();
long byteDone = 0;
int byteCount;
byte[] buffer = new byte[BUFFER_SIZE];
//Connection to file where you want to save the content of shoutcast radio
//It can be skipped in case you dont want to save the contents
out = tempFilecon.openDataOutputStream();
System.out.println("starting download");
while (byteCount = is.read(buffer)) >= 0)
{
out.write(buffer, 0, byteCount);
byteDone += byteCount;
done += byteCount;
}
return;
}
catch (InterruptedIOException e)
{
System.out.println("InterruptedIOException 1" + e.getMessage());
return;
}
catch (Exception e)
{
System.out.println("ERROR - 51 " + e.getMessage());
return;
}
finally
{
if (dos_ != null)
{
dos_.close();
dos_ = null;
}
if (os_ != null)
{
os_.close();
os_ = null;
}
if (is != null)
{
is.close();
is = null;
}
if (out != null)
{
out.close();
out = null;
}
System.out.println("closing connection");
if (connection != null)
{
connection.close();
connection = null;
}
}
// return false;
}

how to upload audio to server: Blackberry

I'm trying to upload an .amr file to the server. My Code as follows:
private static void uploadRecording(byte[] data) {
byte[] response=null;
String currentFile = getFileName(); //the .amr file to upload
StringBuffer connectionStr=new StringBuffer("http://www.myserver/bb/upload.php");
connectionStr.append(getString());
PostFile req;
try {
req = new PostFile(connectionStr.toString(),
"uploadedfile", currentFile, "audio/AMR", data );
response = req.send(data);
} catch (Exception e) {
System.out.println("====Exception: "+e.getMessage());
}
System.out.println("Server Response : "+new String(response));
}
public class PostFile
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;
public PostFile(String url, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
String boundaryMessage = getBoundaryMessage(boundary, fileField, fileName, fileType);
String endBoundary = "\r\n--" + boundary + "--\r\n";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(boundaryMessage.getBytes());
bos.write(fileBytes);
bos.write(endBoundary.getBytes());
this.postBytes = bos.toByteArray();
bos.close();
}
String getBoundaryString()
{
return BOUNDARY;
}
String getBoundaryMessage(String boundary, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
return res.toString();
}
public byte[] send(byte[] fileBytes) throws Exception
{
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH ,Integer.toString(fileBytes.length));
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
dout.close();
int ch;
is = hc.openInputStream(); // <<< EXCEPTION HERE!!!
if(hc.getResponseCode()== HttpConnection.HTTP_OK)
{
while ((ch = is.read()) != -1)
{
bos.write(ch);
}
res = bos.toByteArray();
System.out.println("res loaded..");
}
else {
System.out.println("Unexpected response code: " + hc.getResponseCode());
hc.close();
return null;
}
}
catch(IOException e)
{
System.out.println("====IOException : "+e.getMessage());
}
catch(Exception e1)
{
e1.printStackTrace();
System.out.println("====Exception : "+e1.getMessage());
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
System.out.println("====Exception : "+e2.getMessage());
}
}
return res;
}
}
Highlighted above is the code line which throws the exception: Not Connected.
Can somebody tell me what can be done to correct this? Thanks a lot.
Updated:
public static String getString()
{
String connectionString = null;
String uid = null;
// Wifi
if(WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED)
{
connectionString = ";interface=wifi";
}
else
{
ServiceBook sb = ServiceBook.getSB();
net.rim.device.api.servicebook.ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++) {
if (records[i].isValid() && !records[i].isDisabled()) {
if (records[i].getUid() != null &&
records[i].getUid().length() != 0) {
if ((records[i].getCid().toLowerCase().indexOf("wptcp") != -1) &&
(records[i].getUid().toLowerCase().indexOf("wifi") == -1) &&
(records[i].getUid().toLowerCase().indexOf("mms") == -1) ) {
uid = records[i].getUid();
break;
}
}
}
}
if (uid != null)
{
connectionString = ";deviceside=true;ConnectionUID="+uid;
}
else
{
// the carrier network
if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT)
{
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
// Has carrier coverage, but not BIBS. So use the
// carrier's
// TCP network
System.out.println("No Uid");
connectionString = ";deviceside=true";
} else {
// otherwise, use the Uid to construct a valid carrier
// BIBS
// request
System.out.println("uid is: " + carrierUid);
connectionString = ";deviceside=false;connectionUID="
+ carrierUid + ";ConnectionType=mds-public";
}
}
//(BlackBerry Enterprise Server)
else if((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS)
{
connectionString = ";deviceside=false";
}
// If there is no connection available abort to avoid bugging
// the user unnecessarily.
else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
System.out.println("There is no available connection.");
}
// In theory, all bases are covered so this shouldn't be
// reachable.
else {
System.out.println("no other options found, assuming device.");
connectionString = ";deviceside=true";
}
}
}
return connectionString;
}
/**
* Looks through the phone's service book for a carrier provided BIBS
* network
*
* #return The uid used to connect to that network.
*/
private static String getCarrierBIBSUid() {
try {
net.rim.device.api.servicebook.ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals(
"ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
} catch (Exception e) {
System.out.println("====Exception : "+e.toString());
}
return null;
}

J2ME, Nokia, HttpConnection

This code works fine on SonyEricsson and Motorola cellphones, but on Nokia it either fails at the beginnig not making any request at all or returns empty response, depending on model.
HttpConnection hc = null;
InputStream is = null;
InputStreamReader isr = null;
String result = "";
try
{
hc = (HttpConnection) Connector.open(url);
int rc = hc.getResponseCode();
if (rc != HttpConnection.HTTP_OK)
{
throw new IOException(hc.getResponseMessage());
}
is = hc.openInputStream();
isr = new InputStreamReader(is, "utf-8");
int ch;
while ((ch = is.read()) != -1)
{
result += (char) ch;
}
}
finally
{
if (is != null)
{
is.close();
}
if (hc != null)
{
hc.close();
}
}
return result;
Tried different codes with byte buffers, streams, etc, result is always the same. What's the problem?
try it
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
public class Transport {
public static int BUFFER_LENGTH = 100;//1024;
public static boolean USE_FLUSH = false;
static {
if (DeviceDetect.getDeivice() == DeviceDetect.SAMSUNG) {
BUFFER_LENGTH = 1024;
USE_FLUSH = true;
}
}
public static String SESSION_COOKIE = null;
private static int rnd = 1;
private static final String request(String url, String method, Hashtable params) throws IOException {
HttpConnection conn = null;
DataOutputStream dos = null;
InputStream in = null;
try {
String encodedParams = null;
if (params != null && params.size() > 0) {
encodedParams = getEncodedParams(params);
}
if (method == null) {
if (encodedParams.length() < 2000) {
method = "GET";
} else {
method = "POST";
}
}
method = method != null && method.equalsIgnoreCase("POST") ? HttpConnection.POST : HttpConnection.GET;
if (method.equalsIgnoreCase(HttpConnection.GET)) {
if (encodedParams != null) {
url += (url.indexOf("?") == -1 ? "?" : "&") + encodedParams;
encodedParams = null;
}
url += (url.indexOf("?") == -1 ? "?" : "&") + "_rnd=" + rnd++;
}
conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
if (conn == null) {
throw new IOException("HttpConnection is null, please check Access Point configuration");
}
conn.setRequestMethod(method);
conn.setRequestProperty("User-Agent", UserAgent.getUserAgent());
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (SESSION_COOKIE != null) {
conn.setRequestProperty("Cookie", SESSION_COOKIE);
}
byte[] buff = new byte[BUFFER_LENGTH];
if (encodedParams != null) {
byte[] bytes = encodedParams.getBytes("UTF-8");
String lengthStr = bytes.length + "";
conn.setRequestProperty("Content-Length", lengthStr);
dos = conn.openDataOutputStream();
if (dos == null) {
throw new IOException("OutputStream is null, please check Access Point configuration");
}
for (int i = 0, l = bytes.length; i < l; i += Transport.BUFFER_LENGTH) {
if (Transport.BUFFER_LENGTH == 1) {
dos.writeByte(bytes[i]);
} else {
int count = Math.min(Transport.BUFFER_LENGTH, l - i);
System.arraycopy(bytes, i, buff, 0, count);
dos.write(buff, 0, count);
}
if (Transport.USE_FLUSH) {
dos.flush();
}
}
dos.flush();
try {
dos.close();
} catch (IOException ex) {
}
}
String setCookie = conn.getHeaderField("Set-Cookie");
if (setCookie != null) {
int ind1 = setCookie.indexOf("JSESSIONID=");
if (ind1 > -1) {
int ind2 = setCookie.indexOf(";", ind1);
SESSION_COOKIE = ind2 == -1 ? setCookie.substring(ind1) : setCookie.substring(ind1, ind2 + 1);
}
}
in = conn.openInputStream();
if (in == null) {
throw new IOException("InputStream is null, please check Access Point configuration");
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = in.read(buff);
while (n > -1) {
baos.write(buff, 0, n);
n = in.read(buff);
}
baos.flush();
baos.close();
String response = new String(baos.toByteArray(), "UTF-8");
try {
in.close();
} catch (Exception ex) {
}
try {
conn.close();
} catch (Exception ex) {
}
return response;
} finally {
try {
dos.close();
} catch (Exception ex) {
}
try {
in.close();
} catch (Exception ex) {
}
try {
conn.close();
} catch (Exception ex) {
}
}
}
public static String getEncodedParams(Hashtable params) throws IOException {
String str = "";
Enumeration keys = params.keys();
while (keys.hasMoreElements()) {
String name = (String) keys.nextElement();
Object value = params.get(name);
if (value == null || name == null) {
continue;
}
str += "&" + URLEncoder.encode(name.toString(), "UTF-8") + "=" + URLEncoder.encode(value.toString(), "UTF-8");
}
if (str.length() > 1) {
str = str.substring(1);
}
return str;
}
}
I am not sure if this will work for you but I had a similar problem and found that specifying a port number made it work (on some older Nokia models). i.e convert:
http://www.mysite.com/my_page.html
to:
http://mysite.com:80/my_page.html

Resources