I tried to make HttpConnection of URL through GPRS (Mobile network) on real device but it doesn't return data, but I the same code working well through wireliess, the code also working well on simulator
My code is
public static String getHttpUTFResponse(String url) {
HttpConnection connection = null;
byte responseData[] = null;
try {
connection = (HttpConnection) new ConnectionFactory()
.getConnection(url).getConnection();
int len = (int) connection.getLength();
System.out.println(len);
if (len != -1) {
responseData = new byte[len];
DataInputStream dis;
dis = new DataInputStream(connection.openInputStream());
dis.readFully(responseData);
dis.close();
}
} catch (IOException e) {
System.out.println("Connection Error");
} finally {
if (connection != null) {
try {
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection = null;
}
}
if (responseData != null) {
try {
return new String(responseData,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
Note: the device browser working well and BB service was registered
Thanks to any one
I am moving my comments to these answer:
In Blackberry setting up the connection url for wireless / gprs / 3g / simulator is pretty challenging, please follow the below pointers
For WiFi on device, make sure you have suffixed ";interface=wifi" to the connection url
For GPRS / 3G on device, make sure you have suffixed ";deviceside=false;connectionUID=" for BIS and ";deviceside=false" for BES to the connection URL
More descriptive explanation can be found at:
Need Clarification ---- Http Connection/GPRS
How to configure an IT Policy on the BlackBerry Enterprise Server to allow only the Internet Browser on the BlackBerry smartphone
Internet Connectivity (APN?)
Tag: APN
Different ways to make an HTTP or socket connection
EDIT: Link 5 was useful for OP
try this..
this will help you to detect the simulator, wifi and gprs connection
getWap2Uid();
String url = "your url";
if(DeviceInfo.isSimulator() == true)
{
conn = (StreamConnection) Connector.open(url+ ";deviceside=true");
}
else
{
if (uid != null)
{
//open a WAP 2 connection
conn = (StreamConnection) Connector.open(url + ";deviceside=true;ConnectionUID=" + uid);
}
else
{
//Consider another transport or alternative action.
conn = (StreamConnection) Connector.open(url +";deviceside=true;interface=wifi");
}
}
getWap2Uid function is here
public static String uid ;
static String getWap2Uid() {
ServiceRecord[] records = ServiceBook.getSB().findRecordsByCid("WPTCP");
for (int i = 0; i < records.length; i++)
{
ServiceRecord serviceRecord = records[i];
String recordName = serviceRecord.toString().toUpperCase();
if (serviceRecord.isValid() && !serviceRecord.isDisabled() &&
serviceRecord.getUid() != null && serviceRecord.getUid().length() != 0 &&
recordName.indexOf("WAP2")!=-1)
{
uid = serviceRecord.getUid();
EventLogger.logEvent(EventLogID, new String("getWap2Uid, UID="+uid).getBytes() );
return uid;
}
}
return null;
}
Related
I have java application deployed in weblogic the principal role from app is the communication with another API via socket. This another API is installed in another server. Ok
Sometime to here the java app started getting incomplete data from socket. I have analyzed the logs on the API side. The API return complete data but on weblogic server where java app is deployed not read complete data. Locally the java app work as well.
I suppose that it have something with server memory. I have no idea to solve this problem.
I search on google but have no answers.
Below this original message returned locally with succes:
#**#0 100-Autorizado o uso da NF-e 33170845242914003465652000000007511200000067 http://www4.fazenda.rj.gov.br/retrieve/QRCode?chNFe=33170845242914003465652000000007511200000067&nVersao=100&tpAmb=2&cDest=12345678998&dhEmi=323031372d30382d31385431333a30343a32302d30333a3030&vNF=110.00&vICMS=22.80&digVal=6b6e3774696b652f616b4878574a35414d766367347074497a62343d&cIdToken=000001&cHashQRCode=998144c803f3f5e56a0e1764647ccd6928c2a70d 333170000817607|2017-08-18T13:04:23-03:00|SVRSnfce201707171030|100 http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode? 6989*##*
Below is message returned in weblogic server incomplete:
#**#0 100-Autorizado o uso da NF-e 33170845242914003465652000000007501000000449 http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode?chNFe=33170845242914003465652000000007501000000449&nVersao=100&tpAmb=2&cDest=22233344405&dhEmi=323031372d30382d31385431323a35343a30342d30333a3030&vNF=325.00&vICMS=61.75&digVal=7955796b6b4e64687a7342335470755166495847516c4343566e453d&cIdToken=000001&cHashQRCode=03e10ca5299ed5cb5acd7de5dc5db98df9c49d0e 333170000817573|2017-08-18T12:54:06-03:00|SVRSnfce201707171030|100 http://www4.fazenda.rj.go
Below is responsible class to send and read data:
#Repository
public class SocketRepository implements BaseRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(SocketRepository.class);
private Socket socket;
private static int BUFFER_SIZE = 2048;
private BufferedOutputStream bos;
private BufferedInputStream bis;
#Override
public synchronized String sendDataSocket(String buff, final OsbRequestDTO osbDto) throws Exception {
try {
LOGGER.info("start send data. ");
URL url = new URL(osbDto.getEmissor().getUrlLoja());
openConnection(url.getHost(), url.getPort());
if (this.bos == null) {
this.bos = new BufferedOutputStream(this.socket.getOutputStream(), BUFFER_SIZE);
}
if (this.bis == null) {
this.bis = new BufferedInputStream(this.socket.getInputStream(), BUFFER_SIZE);
}
this.bos.write(buff.getBytes(StandardCharsets.UTF_8));
this.bos.flush();
LOGGER.info("end send data. ");
return readMessagePaperless(bis);
} catch (Exception e) {
LOGGER.error("Erro :" + e.getMessage());
throw e;
} finally {
LOGGER.info("start finally block. ");
closeConnection();
LOGGER.info("End finally block.");
}
}
private String readMessagePaperless(final BufferedInputStream bis) throws IOException {
try {
LOGGER.info("start read data .");
byte[] bufferSize = new byte[512 * 1024];
int data = bis.read(bufferSize);
if (data == -1) {
return "";
}
LOGGER.info("end read data.");
return new String(bufferSize, 0, data, StandardCharsets.UTF_8);
} catch (Exception e) {
LOGGER.error("err." + e.getMessage());
throw e;
}
}
private void closeConnection() throws Exception {
try {
if (this.bos != null && this.bis != null) {
try {
this.bos.close();
this.bis.close();
} catch (Exception e) {
LOGGER.error("err :" + e.getMessage());
throw e;
}
}
if (this.socket == null) {
return;
}
this.socket.close();
this.socket = null;
this.bis = null;
this.bos = null;
} catch (Exception e) {
LOGGER.error("err :" + e.getMessage());
throw e;
}
}
private void openConnection(final String host, final int port) throws UnknownHostException, IOException {
LOGGER.info("start open socket conn.");
if (this.socket != null) {
return;
}
this.socket = new Socket(host, port);
LOGGER.info("end.");
}
}
The read will only read a chunk of data as provided by the network, normally around 1500 bytes depending on various factors. You should continue reading until you have received the complete message. When the connection is local it works differently.
We are getting some very weird behavior in Android. Our network stack (that talks to a REST server) works fine in almost all situations, except when we do a GET shortly after doing a larger POST. What appears to be happening is that the Output stream is not flushing, and ends up sending the last line that was in there when the new socket is opened. Please note, each connection is a new object created, so this is unexpected behavior. First, the error code that seems to point me to the output stream, these are from the server logs.
10.1.8.195 - - [07/Nov/2012:13:36:28 -0700] "POST /iou/lender HTTP/1.1" 200 28 "-" "Android"
10.1.8.195 - - [07/Nov/2012:13:36:36 -0700] "------------V2ymHFg03ehbqgZCaKO6jy" 400 173 "-" "-"
That attempt after should be a GET that then pulls the data from the server that includes the new entry added via the POST. However, all we get is again what appears to be the last line from the output stream from the POST. Here is our core code for the network stack, if more of the surrounding code is needed, let me know.
public Object serverConnect(String url, String method,
Hashtable<String, Object> params) {
HttpConnection c = null;
InputStream is = null;
OutputStream out = null;
ByteArrayOutputStream postDataByteArrayImage = new ByteArrayOutputStream();
byte[] data;
String boundry = "----------V2ymHFg03ehbqgZCaKO6jy";
try {
if (!url.startsWith("/")) {
url = "/" + url;
}
String uri = Control.URL_Secure + Control.dtserver + ":"
+ Control.port + url;
ByteArrayOutputStream postDataByteArray = new ByteArrayOutputStream();
params.put("sessionId", Control.sessionId);
if (method.equals("GET")) {
uri = uri + "?";
Enumeration enumParams = params.keys();
while (enumParams.hasMoreElements()) {
if (!uri.endsWith("?")) {
uri = uri + "&";
}
String key = (String) enumParams.nextElement();
uri = uri
+ key
+ "="
+ java.net.URLEncoder.encode((String) params
.get(key));
}
} else if (method.equals("POST")) {
Enumeration enumParams = params.keys();
postDataByteArray.write(("--").getBytes());
postDataByteArray.write((boundry).getBytes());
postDataByteArray.write(("\r\n").getBytes());
while (enumParams.hasMoreElements()) {
String key = (String) enumParams.nextElement();
if (!key.equals("image")){
postDataByteArray
.write(("Content-Disposition: form-data; name=\"")
.getBytes());
postDataByteArray.write((key).getBytes());
postDataByteArray.write(("\"").getBytes());
postDataByteArray.write(("\r\n\r\n").getBytes());
postDataByteArray.write(((String) params.get(key))
.getBytes());
postDataByteArray.write(("\r\n").getBytes());
postDataByteArray.write(("--").getBytes());
postDataByteArray.write(boundry.getBytes());
postDataByteArray.write(("\r\n").getBytes());
}
}
postDataByteArray.close();
}
Log.i("URL", uri);
URL urltoConenct = new URL(uri);
URLConnection connection = urltoConenct.openConnection();
HttpURLConnection urlConnection = (HttpURLConnection) connection;
URLConnection.setDefaultRequestProperty("Method", method); // default
urlConnection.setRequestProperty("User-Agent", "Android");
if (method.equals("POST")) {
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(postDataByteArray.toByteArray().length + postDataByteArrayImage.toByteArray().length);
urlConnection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundry);
out = urlConnection.getOutputStream();
out.write(postDataByteArray.toByteArray());
out.write(postDataByteArrayImage.toByteArray());
out.close();
}
int response = 0;
try {
response = urlConnection.getResponseCode();
} catch (IOException e) {
if (e.toString()
.equals("java.io.IOException: Received authentication challenge is null"))
throw new RESTException(401, "Invalid Phone or Pin");
else
throw e;
}
if (response == HttpURLConnection.HTTP_OK) {
is = urlConnection.getInputStream();
if (is == null) {
return new IOException(
"Cannot open HTTP InputStream, aborting");
}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int ch;
int count = 0;
while ((ch = is.read()) != -1) {
bo.write(ch);
count++;
}
data = bo.toByteArray();
return new String(data);
} else if (response == 500) {
return new RESTException(500, "Internal server error");
} else {
RESTException x = new RESTException();
x.setCode(response);
try {
is = urlConnection.getInputStream();
if (is == null) {
x.setMessage("Unable to retrieve message");
return x;
}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int ch;
int count = 0;
while ((ch = is.read()) != -1) {
bo.write(ch);
count++;
}
data = bo.toByteArray();
String output = new String(data);
JSONObject obj;
try {
obj = new JSONObject(output);
JSONObject err = obj.getJSONArray("errors")
.getJSONObject(0);
x.setMessage(err.getString("message"));
} catch (JSONException e) {
Log.e("stuff", output);
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// Damn you android! I'm using a REST service here, stop
// trying to interpret my errors!
x.setMessage("Unable to retrieve message");
}
return x;
}
} catch (Exception x) {
x.printStackTrace();
/*
* if (!retried && x.toString().equals(
* "java.io.IOException: Persistent connection dropped after first chunk sent, cannot retry"
* )) { retry = true; } if (!retry) { return x; }
*/
return x;
} finally {
try {
out.close();
} catch (Exception x) {
}
try {
is.close();
} catch (Exception x) {
}
try {
c.close();
} catch (Exception x) {
}
params.clear();
}
// return null;
}
After a very long time of frustration, we discovered that Android tries to keep a connection alive even if you manually call .close() on the connection. This worked fine for our GET methods, but POST methods left the socket in a state that it couldn't then process a GET. Adding the following fixed all our problems:
urlConnection.setRequestProperty("connection", "close");
I am trying to make http request on blackberry platform, My problem is: When I make connection via WiFi it works good, but when I use mobile network it doesn't work and the connection freeze
Here is my code
public static String getHttpUTFResponse(String url) {
url = addConnSuffex(url);
HttpConnection connection = null;
byte responseData[] = null;
try {
connection = (HttpConnection) new ConnectionFactory()
.getConnection(url).getConnection();
int len = (int) connection.getLength();
System.out.println(len);
if (len != -1) {
responseData = new byte[len];
DataInputStream dis;
dis = new DataInputStream(connection.openInputStream());
dis.readFully(responseData);
dis.close();
}
} catch (IOException e) {
System.out.println("Connection Error");
} finally {
if (connection != null) {
try {
connection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection = null;
}
}
if (responseData != null) {
try {
return new String(responseData, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
} else {
return null;
}
}
public static String addConnSuffex(String url) {
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.findRecordsByCid("WPTCP");
String uid = null;
if (records == null) {
return url;
}
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].getUid().toLowerCase().indexOf("wifi") == -1)
&& (records[i].getUid().toLowerCase()
.indexOf("mms") == -1)) {
uid = records[i].getUid();
break;
}
}
}
}
if (DeviceInfo.isSimulator()) {
return url;
}
if (uid != null) {
// open a WAP 2 connection
url = url + ";deviceside=true;ConnectionUID=" + uid;
System.out.println("**************** on conn" + url);
} else {
url = url + ";deviceside=true;interface=wifi";
// Consider another transport or alternative action.
}
System.out.println("**************** on conn" + url);
return url;
}
Thanks a lot
For network connection TransportDetective.class is more use full you can resolve lot of problem related to network.
TransportDetective y URLFactory para configurar la conexion a web
Different ways to make an HTTP or socket connection
I have a working HTTP Proxy server. it can properly handle website using only HTTP and could also connect to HTTPS website. It can properly negotiate with the client's CONNECT request and start connecting to the destination server. now my problem is with some of HTTPS website that requires user login such as facebook and yahoo (though some site, I can do it successfully). it seems i could not properly forward messages coming from both side.(client and server)
what happen is everytime I try logging in to the said site. The browser behave it has successfully log in my account but instead of displaying the actual page, it returns to the login page.
here is how my code work
// Daemon Class
while(true)
{
ConnectionHandler handler = new ConnectionHandler(server.accept());
handler.start();
}
// ConnectionHandler class
class ConnectionHandler extends Thread
{
Socket client = null;
Socket server = null;
HTTPRequestHdr request = null;
public ConnectionHandler(Socket socket)
{
client = socket;
request = new HTTPRequestHdr();
}
public void run()
{
try
{
request.parse(client.getInputStream());
server = new Socket(request.url,request.port);
if(request.getMethod().equals("CONNECT");
{
// send 200 message to client then proceed
}
else
{
// send the request to server
}
Tunnel clientToServer = new Tunnel(client,server);
Tunnel ServerToClient = new Tunnel(server,client);
clientToServer.start();
ServerToClient.start();
}catch(Exception e) {}
}
}
// Tunnel class
class Tunnel extends Thread
{
Socket from = null;
Socket to = null;
public Tunnel(Socket from , Socket to)
{
this.from = from;
this.to = to;
}
public void run()
{
OutputStream toClient = null;
InputStream fromClient = null;
byte[] buffer = new byte[50];
int numberRead = 0;
iny noResponse = 0;
try
{
toClient = to.getOutputStream();
fromClient = fro.getInputStream();
int avail = fromClient.available();
if(avail < 1)
{
Thread.sleep(20);
noResponse += 20;
}
else
{
noResponse = 0;
}
while(avail > 0)
{
numberRead = avail;
numberRead = fromClient.read(buffer,0,numberRead);
toClient.write(buffer,0,numberRead);
toClient.flush();
avail = fromClient.available();
}
if(noResponse > 30000)
{
// close connection
}
}catch(Exception e) {}
}
}
I believe I fail to properly forward the data coming from both side. please tell me where
I am wrong and how to fix it?
try
{
int avail = fromClient.available();
if(avail < 1)
{
Thread.sleep(20);
noResponse += 20;
}
else
{
noResponse = 0;
}
while(avail > 0)
{
numberRead = avail;
numberRead = fromClient.read(buffer,0,numberRead);
toClient.write(buffer,0,numberRead);
toClient.flush();
avail = fromClient.available();
}
if(noResponse > 30000)
{
// close connection
}
} catch(Exception e) {}
This is all wrong. Sockets already have a timeout facility, and you are just wasting time calling available() and sleep(). All you need is this:
try
{
fro.setSoTimeout(30000);
while ((length = fromClient.read(buffer)) > 0)
{
toClient.write(buffer, 0, length);
}
// close sockets
toClient.close();
fromClient.close();
}
catch (SocketTimeoutException exc)
{
// handle timeout, and certainly close the socket
}
catch (IOException exc)
{
// exception handling
}
finally
{
fro.close(); // close the input socket, NB not the output socket, the other thread will do that
}
I am trying to connect to a URL through a Java program in Blackberry simulator. But it is not connecting.
try {
HttpConnection httpConn;
StreamConnection s;
s = (StreamConnection)Connector.open("http://www.google.com/");
httpConn = (HttpConnection)s;
status = httpConn.getResponseCode();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int t=0;
if (status == HttpConnection.HTTP_OK)
{
add(new RichTextField("Successfully Authorized", Field.NON_FOCUSABLE));
}
s = (StreamConnection)Connector.open("http://www.google.com"+";deviceside=true");
try with this line...
If you are trying in emulator means use deviceside=true
If its in a mobile means for wifi connection you have to use interface=wifi