HttpConnection.getResponseCode() return -1
Hi guy's
I am developing a midp application which is communicate with server and display the result on the client using HttpConnection.Basically i am from bangalore,India and using Airtel,Vodafone connections for GPRS. My jar file is properly working in the Sony Ericsson models(k800i,k310i) with airtel and vodafone connections. But the same jar file is failed to communicate with server in Nokia models. HttpConnection.getResponseCode() return -1 in Nokia 6020,6070,6300 devices. Even N6030 is also return same value with vodafone. But same time application working fine in another 6030 model with airtel. Please look at my source code below.
private static String requestToServer(final String url, final String data)throws IOException {
HttpConnection httpCon = null;
InputStream inputStream = null;
String result = null;
try {
while (true) {
httpCon = (HttpConnection) Connector.open(connectionUrl,Connector.READ_WRITE);
httpCon.setRequestMethod(HttpConnection.POST);
final String conf = System.getProperty("microedition.configuration");
final String prof = System.getProperty("microedition.profiles");
httpCon.setRequestProperty("User-Agent","Profile/" + prof + " Configuration/" + conf);
writeDataToConnection(httpCon, data);
if (!isRedirectResponse(httpCon)) {
break;
connectionUrl = httpCon.getHeaderField("Location");
httpCon.close();
inputStream = httpCon.openInputStream();
result = readStreamData(inputStream);
} catch (final ClassCastException e) {
throw new IllegalArgumentException("Not an HTTP URL"); }
catch (final IOException e) { throw e; }
catch (final Exception e) { throw e; }
finally {
if (inputStream != null) { inputStream.close(); }
if (httpCon != null) { httpCon.close(); }
return result;
private static void writeDataToConnection(final HttpConnection c, final String data) throws IOException {
final OutputStream os = c.openOutputStream();
try {
final DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(data);
dos.flush();
catch(IOException e) { throw e; }
finally { os.close(); }
private static boolean requestToServer(final HttpConnection httpCon)throws IOException {
boolean result = false;
final int conResponseCode = httpCon.getResponseCode();
switch (conResponseCode) {
case HttpConnection.HTTP_OK:
result = false;
break;
case HttpConnection.HTTP_MOVED_TEMP:
if (DEBUG_REDIRECT) {
System.out.println("Request is redirected"); }
result = true;
break;
default:
throw new IOException("HTTP response code: " + conResponseCode);
return result;
In the Nokia models, the httpCon.getResponseCode() return -1. Can anybody tell me, whats the problem and what the solution for this please.
Regards,
Jobin
use this ---> return new int[]{1,3};
Similar Messages
-
HttpConnection.getResponseCode - MIDP bug?
Hi!
Try the following:
-make some example trying to connect to a valid Url...
-verify your connection...
-now make sure that is working properly.
-turn off your Ethernet cable or ISP connection
-Try to run the same example now.
The IOException is raised.... Iwonder Why??? The returned response code should be 503 HTTP_UNAVAILABLE .... Is this a MIDP bug or am I missing something?
public boolean verifyConnection(HttpConnection conn) throws IOException
boolean res=false;
if (conn==null)
sConError="Null Connection";
res=false;
else
//System.out.println("1a" + conn.getURL() + conn.getResponseMessage());
int rc;
rc=conn.getResponseCode(); //Here's the problem when I'am not connected to the internet and try to make a Connection to an outside Site....
sConError="";
switch( rc )
case HttpConnection.HTTP_OK:
res=true;
break;
case HttpConnection.HTTP_TEMP_REDIRECT:
res=true;
break;
case HttpConnection.HTTP_ENTITY_TOO_LARGE:
res=false;
break;
default:
sConError=conn.getResponseMessage();
res=false;
break;
System.out.println("3a");
return res;
MarcoI could be wrong on this....
The response code comes from the web server. If you disconnect your internet connection your MIDlet is no longer able to establish a connection to the web-server therefore it gets an IOException. -
GetResponseCode() returns -1,what does it mean
Hi ,
The HttpURLConnection class's getResponseCode() method returns -1.
getResponseMessage() returns null.i m accessing my servlet through a proxy.i know only about 1xx to 5xx codes.i dont know what does it mean by -1.But at server side the request is properly sent and processed and i m getting 200 and ok after processing at serverside. the object is sent to client also. but it is not received by the client.
Null object is returned.I think proxy is the culprit.If anyone can help me what -1 means,it will be really greatfull to diagnoise my issue in detail and solve my problem soon.
Your help will be greatfull.
Thanks
prakashAs it says perfectly clearly, right there in the API documentation for the method:
"Returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP)." -
HttpConnection.getResponseCode generates a Connection Refused exeption
I have the following problem:
I connect to a webserver, this works fine. Then I write data to the webserver, this also works fine. After writing the data, I determine the http response code to see if everything was successfull. Every so often this generates a "connection refused" exception. This happens even after the connect and the write were successfull. I find this strange, since I was able to connect and write data (this data has arrived at the server because I can log it there without a problem).
Can anyone explain this behaviour to me, because I am lost here.
MarkHave found that wildcard addresses matches any address of the local system, and that in IPv4, the wildcard address is 0.0.0.0. Can check for this with InetAddress.isAnyLocalAddress().
This means that I could potentially handle these cases by adding code to "ping" a host such as "tigers.com.au" using
InetAddress address = InetAddress.getByName(name);
if (InetAddress.isAnyLocalAddress() {
.... do something, eg raise exception
}But this is not fully satisfactory, as I would rather know that a "connection refused" exception is raised, which is actually the case with "tigers.com.au" (as all the browsers seem able to detect). I am not entirely sure what the relationship is between a site that has "connection refused" and it returning an ip address of 0.0.0.0. I don't think they are synonymous.
Any thoughts? -
HttpConnection hangs in my T630. Please Help !
Hi all,
I`ve noticed this problem in a few threads on this forum, but none of them seem to have a definitive answer. Maybe we can answer it once and for all here :-) Any help would be greatly appreciated.
I`m trying to load a web page from a midlet in my T630. As I don`t really want to pay for call charges during development, I`m using the "Device Explorer" and the "Connection proxy" to try and connect to the internet using my broadband connection. I'm using the SonyEricsson developer kit (version 1) and I'm using a bluetooth serial connection on COM5 for the connection proxy.
I've based my code on some sample code from Sun to load some info from a web page. This code was even published to get around the IO blocking problem that I seem to be getting still !
The problem is when I try and use the HttpConnection.getResponseCode() method. Using the advice of other internet resources, I`ve put this code in its own thread. When I call HttpConnection.getResponseCode(), my T630 then pops ups with a menu, offering me these 3 options:
Allow Web access
Ask per access
Deny Web access
When this happens, it`s as if the thread running the getResponseCode() method blocks, and the T630 OS takes over. When I select an item from that menu, control does not pass back to the thread running getResponseCode(), but goes to the main midlet thread. Once I`m back in the main midlet thread, I don't know how to wake up the url loading thread. Does anyone have any ideas.
My debugging statements produce the following before the app hangs:
url=http://java.sun.com
conn=com.sun.midp.io.j2me.http.Protocol@e4857a1d
here
Connecting to http://java.sun.comHere is the source code:
package com.pg.midp.http;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
// Simple class that connects to a given URL and
// prints out the response code and any headers
// that are sent back. Shows how to use background
// threads to make HTTP connections while keeping the
// user interface alive.
public class HttpLogger extends MIDlet
private Display display;
private Command exitCommand = new Command([quot][/quot]Exit[quot][/quot], Command.EXIT, 1);
private Command okCommand = new Command([quot][/quot]OK[quot][/quot], Command.OK, 1);
private Command cancelCommand = new Command([quot][/quot]Cancel[quot][/quot], Command.CANCEL, 1);
private URLEntry mainForm;
// Standard MIDlet stuff....
public HttpLogger()
protected void debug(String s)
System.out.println(s);
protected void destroyApp(boolean unconditional) throws MIDletStateChangeException
exitMIDlet();
protected void pauseApp()
protected void startApp() throws MIDletStateChangeException
if (display == null)
initMIDlet();
private void initMIDlet()
display = Display.getDisplay(this);
mainForm = new URLEntry();
display.setCurrent(mainForm);
public void exitMIDlet()
notifyDestroyed();
// Utility routine to display exceptions.
void displayError(Throwable e, Displayable next)
Alert a = new Alert([quot][/quot]Exception[quot][/quot]);
a.setString(e.toString());
a.setTimeout(Alert.FOREVER);
display.setCurrent(a, next);
// Simple entry form for entering the URL to
// connect to.
class URLEntry extends TextBox implements CommandListener
URLEntry()
super([quot][/quot]Enter URL:[quot][/quot], [quot][/quot]java.sun.com[quot][/quot], 100, 0);
addCommand(exitCommand);
addCommand(okCommand);
setCommandListener(this);
public void commandAction(Command c, Displayable d)
if (c == exitCommand)
exitMIDlet();
else if (c == okCommand)
try
String url = [quot][/quot]http://[quot][/quot] + getString();
debug([quot][/quot]url=[quot][/quot] + url);
HttpConnection conn = (HttpConnection) Connector.open(url);
debug([quot][/quot]conn=[quot][/quot] + conn);
Logger logger = new Logger(this, conn);
debug([quot][/quot]here[quot][/quot]);
display.setCurrent(logger);
catch (IOException e)
displayError(e, this);
// Simple form that contains a single string item.
// The string item is updated with status messages.
// When constructed, it starts a background thread
// that makes the actual HTTP connection. Displays
// a Cancel command to abort the current connection.
class Logger extends Form implements Runnable, CommandListener
private Displayable next;
private HttpConnection conn;
private StringItem text = new StringItem(null, [quot][/quot][quot][/quot]);
boolean done = false;
Thread t;
Logger(Displayable next, HttpConnection conn)
super([quot][/quot]HTTP Log[quot][/quot]);
this.next = next;
this.conn = conn;
addCommand(cancelCommand);
setCommandListener(this);
append(text);
t = new Thread(this);
t.start();
// Handle the commands. First thing to do
// is switch the display, in case closing/
// the connection takes a while...
public void commandAction(Command c, Displayable d)
display.setCurrent(next);
try
conn.close();
catch (IOException e)
displayError(e, next);
// Do the connection and processing on
// a separate thread...
public void run()
try
update([quot][/quot]Connecting to [quot][/quot] + conn.getURL());
try
int rc = conn.getResponseCode();
update([quot][/quot]Response code: [quot][/quot] + rc);
update([quot][/quot]Response message: [quot][/quot] + conn.getResponseMessage());
String key;
for (int i = 0; (key = conn.getHeaderFieldKey(i)) != null; ++i)
update(key + [quot][/quot]: [quot][/quot] + conn.getHeaderField(i));
catch (IOException e)
update([quot][/quot]Caught exception: [quot][/quot] + e.toString());
catch (Exception e)
debug(e.getMessage());
e.printStackTrace();
finally
done = true;
removeCommand(cancelCommand);
addCommand(okCommand);
// Update the string item with new information.
// Only do it if we're actually visible.
void update(String line)
debug(line);
if (display.getCurrent() != this)
return;
String old = text.getText();
StringBuffer buf = new StringBuffer();
buf.append(old);
if (old.length() [gt][/gt] 0)
buf.append('\n');
buf.append(line);
text.setText(buf.toString());
}Thanks,
Paul.Hi, Paulgrime:
These days I also have struggled with the problem.
I just saw a java example from SUN site, which does not use getResponseCode(). It seems a good work around.
I tried that way and works fine. Only thing is you have to figure out the response status by analysing the inputstream content, which is actually easy.
So I go this way now.
Huiyi -
Please help about HttpConnection
Hi all,
I am facing a typical problem about HttpConnection() for BlackBerry.But it is working fine in all other devices except BlackBerry.Bellow is the code:
public synchronized String getResponse(String sRequest)
String sReturn = null;
HttpConnection c = null;
java.io.InputStream is = null;
StringBuffer sb = new StringBuffer();
int ch;
int rc;
try {
sRequest=sRequest.trim();
c = (HttpConnection) Connector.open(sRequest);
c.setRequestProperty("User-Agent", System.getProperty("microedition.profiles"));
c.setRequestProperty("Content-Type", "application/octet-stream");
rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
return null;
is = c.openInputStream();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
is.close();
c.close();
sReturn = sb.toString();
} catch(Exception e) {
System.out.println("URLCatch : "+sRequest);
sReturn = null;
return sReturn ;
}*"sRequest" is a simple URL String without any WAPGatewayIP & WAPGatewayAPN.*
Please tell me what is the wrong inside this connection method? Why this is not establishing the connection in BlackBerry? Should i have to change anything in this method for BlackBerry?I tried a lot but colud not solve.
Please help.
Thanks in advanceHello Susanta_Mandal,
How you resolve the HttpConnection issue in balckberry handdheld ? i am facing the same probelm.
I am developing a mobile phone application(J2ME) for a BlackBerry handheld.In this application i use servlets for fetching Data,but when calling the URL it doesnt work and shows the IOException : Timed Out Error. I am using Vodafone sim card (Mumbai India) and it's GPRS is enabled. and I also crosscheck our application with other handsets like Nokia,Samsung etc. using same simcard and it's working fine.
I try to connect the URL in two ways.
1) Connector.open("http://161.117.177.166:8080/temp/chart;deviceside=true);
BlackBerry APN setting for Vodafone
Select Option -- > Advanced Options -> TCP/IP
APN Setting Enabled Checked
APN :portalnmms
Username for APN :Left Blank
Password for APN :Left Blank
Result Is :- IOException : Timed Out.
2) Send APN Parameter along with URL
Connector.open("http://161.117.177.166:8080/temp/chart;ConnectionTimeout=120000;deviceside=true;WapGatewayIP=010.010.001.100;WapGatewayPort=9401;WapGatewayAPN=portalnmms",Connector.READ_WRITE,true);
Result Is :- net.rim.device.cldc.io.waphttp.WAPIOException
Regard's
Prasanna K -
Need help with my HttpConnection From Midlet To Servlet...
NEED HELP ASAP PLEASE....
This class is supposed to download a file from the servlet...
the filename is given by the midlet... and the servlet will return the file in bytes...
everything is ok in emulator...
but in nokia n70... error occurs...
Http Version Mismatch shows up... when the pout.flush(); is called.. but when removed... java.io.IOException: -36 occurs...
also i have posted the same problem in nokia forums..
please check also...
http://discussion.forum.nokia.com/forum/showthread.php?t=105567
now here are my codes...
midlet side... without pout.flush();
public class DownloadFile {
private GmailMidlet midlet;
private HttpConnection hc;
private byte[] fileData;
private boolean downloaded;
private int lineNumber;
// private String url = "http://121.97.220.162:8084/ProxyServer/DownloadFileServlet";
private String url = "http://121.97.221.183:8084/ProxyServer/DownloadFileServlet";
// private String url = "http://121.97.221.183:8084/ProxyServer/Attachments/mark.ramos222/GmailId111d822a8bd6f6bb/01032007066.jpg";
/** Creates a new instance of DownloadFile */
public DownloadFile(GmailMidlet midlet, String fileName) throws OutOfMemoryError, IOException {
System.gc();
setHc(null);
OutputStream out = null;
DataInputStream is= null;
try{
setHc((HttpConnection)Connector.open(getUrl(), Connector.READ_WRITE));
} catch(ConnectionNotFoundException ex){
setHc(null);
} catch(IOException ioex){
ioex.printStackTrace();
midlet.alertScreen = new AlertScreen("Error C1", ioex.toString(),
null, AlertType.ERROR);
midlet.alertScreen.setTimeout(Alert.FOREVER);
midlet.display.setCurrent(midlet.alertScreen);
try {
if(getHc() != null){
getHc().setRequestMethod(HttpConnection.POST);
getHc().setRequestProperty("Accept","*/*");
getHc().setRequestProperty("Http-version","HTTP/1.1");
lineNumber = 1;
getHc().setRequestProperty("CONTENT-TYPE",
"text/plain");
lineNumber = 2;
getHc().setRequestProperty("User-Agent",
"Profile/MIDP-2.0 Configuration/CLDC-1.1");
lineNumber =3;
out = getHc().openOutputStream();
lineNumber = 4;
PrintStream pout = new PrintStream(out);
lineNumber = 5;
pout.println(fileName);
lineNumber = 6;
// pout.flush();
System.out.println("File Name: "+fileName);
lineNumber = 7;
is = getHc().openDataInputStream();
long len = getHc().getLength();
lineNumber = 8;
byte temp[] = new byte[(int)len];
lineNumber = 9;
System.out.println("len "+len);
is.readFully(temp,0,(int)len);
lineNumber = 10;
setFileData(temp);
lineNumber = 11;
is.close();
lineNumber = 12;
if(getFileData() != null)
setDownloaded(true);
else
setDownloaded(false);
System.out.println("Length : "+temp.length);
midlet.setAttachFile(getFileData());
lineNumber = 13;
pout.close();
lineNumber = 14;
out.close();
lineNumber = 15;
getHc().close();
} catch(Exception ex){
setDownloaded(false);
ex.printStackTrace();
midlet.alertScreen = new AlertScreen("Error C2+ line"+lineNumber,
ex.toString()+
" | ",
null, AlertType.ERROR);
midlet.alertScreen.setTimeout(Alert.FOREVER);
midlet.display.setCurrent(midlet.alertScreen);
public HttpConnection getHc() {
return hc;
public void setHc(HttpConnection hc) {
this.hc = hc;
public String getUrl() {
return url;
public void setUrl(String url) {
this.url = url;
public byte[] getFileData() {
return fileData;
public void setFileData(byte[] fileData) {
this.fileData = fileData;
public boolean isDownloaded() {
return downloaded;
public void setDownloaded(boolean downloaded) {
this.downloaded = downloaded;
}this is the midlet side with pout.flush();
showing Http Version Mismatch
public class DownloadFile {
private GmailMidlet midlet;
private HttpConnection hc;
private byte[] fileData;
private boolean downloaded;
private int lineNumber;
// private String url = "http://121.97.220.162:8084/ProxyServer/DownloadFileServlet";
private String url = "http://121.97.221.183:8084/ProxyServer/DownloadFileServlet";
// private String url = "http://121.97.221.183:8084/ProxyServer/Attachments/mark.ramos222/GmailId111d822a8bd6f6bb/01032007066.jpg";
/** Creates a new instance of DownloadFile */
public DownloadFile(GmailMidlet midlet, String fileName) throws OutOfMemoryError, IOException {
System.gc();
setHc(null);
OutputStream out = null;
DataInputStream is= null;
try{
setHc((HttpConnection)Connector.open(getUrl(), Connector.READ_WRITE));
} catch(ConnectionNotFoundException ex){
setHc(null);
} catch(IOException ioex){
ioex.printStackTrace();
midlet.alertScreen = new AlertScreen("Error C1", ioex.toString(),
null, AlertType.ERROR);
midlet.alertScreen.setTimeout(Alert.FOREVER);
midlet.display.setCurrent(midlet.alertScreen);
try {
if(getHc() != null){
getHc().setRequestMethod(HttpConnection.POST);
getHc().setRequestProperty("Accept","*/*");
getHc().setRequestProperty("Http-version","HTTP/1.1");
lineNumber = 1;
getHc().setRequestProperty("CONTENT-TYPE",
"text/plain");
lineNumber = 2;
getHc().setRequestProperty("User-Agent",
"Profile/MIDP-2.0 Configuration/CLDC-1.1");
lineNumber =3;
out = getHc().openOutputStream();
lineNumber = 4;
PrintStream pout = new PrintStream(out);
lineNumber = 5;
pout.println(fileName);
lineNumber = 6;
pout.flush();
System.out.println("File Name: "+fileName);
lineNumber = 7;
is = getHc().openDataInputStream();
long len = getHc().getLength();
lineNumber = 8;
byte temp[] = new byte[(int)len];
lineNumber = 9;
System.out.println("len "+len);
is.readFully(temp,0,(int)len);
lineNumber = 10;
setFileData(temp);
lineNumber = 11;
is.close();
lineNumber = 12;
if(getFileData() != null)
setDownloaded(true);
else
setDownloaded(false);
System.out.println("Length : "+temp.length);
midlet.setAttachFile(getFileData());
lineNumber = 13;
pout.close();
lineNumber = 14;
out.close();
lineNumber = 15;
getHc().close();
} catch(Exception ex){
setDownloaded(false);
ex.printStackTrace();
midlet.alertScreen = new AlertScreen("Error C2+ line"+lineNumber,
ex.toString()+
" | ",
null, AlertType.ERROR);
midlet.alertScreen.setTimeout(Alert.FOREVER);
midlet.display.setCurrent(midlet.alertScreen);
public HttpConnection getHc() {
return hc;
public void setHc(HttpConnection hc) {
this.hc = hc;
public String getUrl() {
return url;
public void setUrl(String url) {
this.url = url;
public byte[] getFileData() {
return fileData;
public void setFileData(byte[] fileData) {
this.fileData = fileData;
public boolean isDownloaded() {
return downloaded;
public void setDownloaded(boolean downloaded) {
this.downloaded = downloaded;
}here is the servlet side...
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(request.getMethod().equals("POST")){
BufferedReader dataIN = request.getReader();
String fileName = dataIN.readLine();
File file = new File(fileName);
String contentType = getServletContext().getMimeType(fileName);
response.setContentType(contentType);
System.out.println("Content Type: "+contentType);
System.out.println("File Name: "+fileName);
int size = (int)file.length()/1024;
if(file.length() > Integer.MAX_VALUE){
System.out.println("Very Large File!!!");
response.setContentLength(size*1024);
FileInputStream fis = new FileInputStream(fileName);
byte data[] = new byte[size*1024];
fis.read(data);
System.out.println("data lenght: "+data.length);
ServletOutputStream sos = response.getOutputStream();
sos.write(data);
// out.flush();
}else{
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
BufferedReader dataIN = request.getReader();
String msg_uid = dataIN.readLine();
System.out.println("Msg_uid"+msg_uid);
JDBConnection dbconn = new JDBConnection();
String fileName = dbconn.getAttachment(msg_uid);
String[] fileNames = fileName.split(";");
int numFiles = fileNames.length;
out.println(numFiles);
for(int i = 0; i<numFiles; i++){
out.println(fileNames);
out.flush();
out.close();
Message was edited by:
Mark.Ramos2221) Have you looked up the symbian error -36 on new-lc?
2) Have you tried the example in the response on forum nokia?
3) Is the address "121.97.220.162:8084" accessible from the internet, on the device, on the specified port? -
I use HttpURLConnection class to submit a list of values to a servlet,
When I use application to do that,it works.But after I change it to
a servlet,it failed.getResponseCode() return -1 not 200,why?public void SubmitToParty(String reqMethod,String URLStr,String Content)
try
URL UrlInst = new URL(URLStr);
URLConnection MyConn= UrlInst.openConnection();
HttpURLConnection HttpConn = (HttpURLConnection)MyConn;
if(reqMethod.compareTo("GET")==0||reqMethod.compareTo("POST")==0)
HttpConn.setRequestMethod(reqMethod);
HttpConn.setDoOutput(true);
PrintStream out = new PrintStream(HttpConn.getOutputStream());
out.println(Content);
out.close();
System.out.println(HttpConn.getResponseCode());
System.out.println("send data ok!");
catch(Exception URLExp)
System.out.println("Submit to party error!");
URLExp.printStackTrace();
} -
I am writing a mobile client that makes an HTTP Connection and performs a POST to the a Web Services Server. The WS is running .NET. My client works as it should running on all the emulators out there, however, I�m having a problem with an actual device. Then the InputStream is returned but the HTTPConnection.getLength returns >= 0. So I had to make a patch to read the InputStream in chunks and then discard the header section. This results in an �Unexpected End of Input Stream� Exception. Is this going to be a problem with other devices then the one I tested with: The Audiovox SMT-5600? I contacted the vendor but they won�t give any help on outside issues. The headers are getting mixed in with the stream returned. This does not happen on the emulator, the emulator filters out the headers and returns the length of the SOAP message. Here is the following code I have tried to correct this problem. If anyone has run into this issues and can give me some instruction on how to work around this problem I would appreciate it a lot. Thank you in advance!
int length = 0;
HttpConnection hc = null;
OutputStream out = null;
DataInputStream in = null;
hc = (HttpConnection)Connector.open(SOAP_SERIVCE_URL);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
hc.setRequestProperty("Content-Length", Integer.toString(soapMessage.length()));
hc.setRequestProperty("SOAPAction","\"" + soapAction + "\"");
out = hc.openOutputStream();
out.write(soapMessage.getBytes());
in = hc.openDataInputStream();
length = (int)hc.getLength();
byte[] data = new byte[(int)length];
in.read(data);
This does not work because the length is not being returned. I have also tried this:
int length = 0;
HttpConnection hc = null;
OutputStream out = null;
DataInputStream in = null;
hc = (HttpConnection)Connector.open(SOAP_SERIVCE_URL);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
hc.setRequestProperty("Content-Length", Integer.toString(soapMessage.length()));
hc.setRequestProperty("SOAPAction","\"" + soapAction + "\"");
out = hc.openOutputStream();
out.write(soapMessage.getBytes());
in = hc.openDataInputStream();
length = (int)hc.getLength();
if (length <= 0) {
String contentLength = hc.getRequestProperty("Content-Length");
length = Integer.parseInt(contentLength);
byte[] data = new byte[(int)length];
in.read(data);
This works but since the HTTP Headers are in the input stream and not filtered out I don't get the whole SOAP Message. I tried to read the input stream in chunks:
int length = 0;
HttpConnection hc = null;
OutputStream out = null;
DataInputStream in = null;
String response;
hc = (HttpConnection)Connector.open(SOAP_SERIVCE_URL);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
hc.setRequestProperty("Content-Length", Integer.toString(soapMessage.length()));
hc.setRequestProperty("SOAPAction","\"" + soapAction + "\"");
out = hc.openOutputStream();
out.write(soapMessage.getBytes());
in = hc.openDataInputStream();
length = (int)hc.getLength();
if (length > 0) {
gs.setPositionStr("length > 0");
int actual = 0;
int bytesread = 0 ;
byte[] data = new byte[length];
in.readFully(data);
response = new String(data);
} else {
int chunkSize = 512;
int index = 0;
int readLength = 0;
byte[] data = new byte[chunkSize];
do {
if (data.length < index + chunkSize) {
byte[] newData = new byte[index + chunkSize];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
readLength = in.read(data, index, chunkSize);
index += readLength;
} while (readLength == chunkSize);
length = index;
response = new String(data);
response = response.substring(response.indexOf("<?xml") -1); //remove the HTTP headers from the SOAP envelope
This methods gets into the else block because there is no length specified, but it throws an 'Unexpected End of Input Stream' exception. Looking at the response string only a portion of the input stream was read.Think simple! A query to the "Content-Length" won't work if the response is chunked (and it probably is). That's why getLength will return 0.
Solution is much simpler that sun does in the javadocs example codes:
int BUFFERSIZE=128;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFERSIZE]
int bs = 0;
while((bs = in.read(buffer,0,buffer.length)!= -1){
bout.write(buffer,0,bs);
String response = bout.toString();It is always fast, simple, and short :) no if/else crap. Forget the length, and just read until end of stream and convert to String. -
Hello guys!
I tried a lot of times to send chinese characters using HttpConnection in j2me, but I have failed. :(
I tried in this way: I wrote a MIDlet using the HttpConnection, but when the data arrived in the servlet, the servlet receives a <null> String or an other character.
I ask to a friend, and he told me to change the charset using setRequestProperty methos in the HttpConnection.
I changed all values using the charset values from: http://a4esl.org/c/charset.html
but I have failed again, sometimes the MIDlet send a null String, sometimes I got a java.io.UnsupportedEncodingException...
If I sent the characters from the servlet directly to the MIDlet, woks... but I want to get the values from the MIDlet first, and them send the response...
Can anybody help me with this problem?
Thanks in advance.I do not think its a probelm with not specifying encoding format in input stream . I have done a small test for it . I have commented my code of reading the input stream and have just used httpconenctin.dosconnect .
I ahve changed my code to following
for(loop)
String xml request = "xml request..n"
URL url = new URL(Config.getProperty("url"));
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type",
"application/soap; charset=\"utf-8\"");
OutputStream stream = httpConnection.getOutputStream();
stream.write(request.getBytes());
stream.close();
log.debug("Teturned from server::::::::::::::"+ httpConnection.getResponseCode() + "message"
+ httpConnection.getResponseMessage());
httpConnection.disconnect();
}Even with this .. iam getting socket reset exception for multiple requests. The curios part is for sirst request i get the response, but for second request it fails . -
OBIEE integrated to Mapviewer , need advice from expert people in my codes
<!--[if !mso]>
<style>
v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style>
<![endif]--><!--[if gte mso 9]><xml>
Normal
0
false
false
false
MicrosoftInternetExplorer4
</xml><![endif]--><!--[if gte mso 9]><xml>
</xml><![endif]--><!--[if !mso]>
<object
classid="clsid:38481807-CA0E-42D2-BF39-B33AF135CC4D" id=ieooui>
</object>
<style>
st1\:*{behavior:url(#ieooui) }
</style>
<![endif]-->
<!--[if gte mso 10]>
<style>
/* Style Definitions */
table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;}
</style>
<![endif]-->
Based on Example : [http://www.oracle.com/technology/products/mapviewer/pdf/mapviewer_obiee.pdf|blocked::http://www.oracle.com/technology/products/mapviewer/pdf/mapviewer_obiee.pdf]
*1- Using OBIEE , I create report with two fields and it's filter on
field Region:*
Region , Population
<!--[if !mso]>
<style>
v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
</style>
<![endif]--><!--[if gte mso 9]><xml>
Normal
0
false
false
false
MicrosoftInternetExplorer4
</xml><![endif]--><!--[if gte mso 9]><xml>
</xml><![endif]-->
<!--[if gte mso 10]>
<style>
/* Style Definitions */
table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;}
</style>
<![endif]-->
On OBIEE Answers: Statistic Text , I wrote this codes :
<!-div id must match arg in js call at bottom of code listing -->
<div id="EPAmapNode1"></div>
<script>
function readCookie(name) {
//this pulls authentication out of header
//which replaces needing to pass user/pwd
to authenticate (i.e. like SSO or trusted sign on)
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca;
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
return null;
function obiee_mapint_doTheDeed(nodeId) {
var container = document.getElementById(nodeId);
var sid = null;
var x = container;
do {
if (x.nodeName == 'TD' || x.nodeName == 'DIV') {
sid = x.getAttribute('sid');
if (sid != null && sid != '')
break;
x = x.parentNode;
while (x != null);
if (sid != null && sid != '') {
// create the iframe for content
var nid = readCookie('nQuireID')
if (nid) {
var iframe = document.createElement('iframe');
iframe.src =
'http://192.168.100.143:8991/yusufMap-ViewController-context-root/BIMapPage.html?sid='
+ encodeURIComponent(sid) + '&nqid=' + nid;
// following nsdp is subsequently called
from Mapviewer page
// passing sid and nqid to get results to
serve as nsdp data as xml
// ps["xml_url"] = "http://"+document.location.host+"/mapviewer/_epa/obiee_nsdp_xml_direct.jsp?nqid="
+
// urlParamNQID + "&sid=" +
urlParamSID;
iframe.height = 260;
iframe.width = 600;
iframe.frameBorder = 0;
iframe.marginHeight = 1;
iframe.marginWidth = 1;
container.appendChild(iframe);
obiee_mapint_doTheDeed('EPAmapNode1');
// js fn, EPAmapNode1 is id for this map in
dashbd
</script>
*2-Source code of
custom JSP to convert Answers Filtered XML into NSDP XML: obiee_nsdp_xml_direct.jsp*
<%@ page
language="java" session="true"
isThreadSafe="true" contentType="text/html; charset=UTF-8"
%>
<%@ page
import="javax.xml.parsers.*"%>
<%@ page
import="java.net.*"%>
<%@ page
import="java.io.*"%>
<%@ page
import="org.w3c.dom.*"%>
<%
Sample jsp code file to demonstrate one way to convert Answers xml to
MapViewer's NSDP xml
set the character encoding to UTF-8 prior to accessing
data in the request
request.setCharacterEncoding("UTF-8");
%>
<%
// RETRIEVE THE QUERY
STRING PARAMETERS
String userName =
request.getParameter("uid");
String userPassword =
request.getParameter("password");
String thesid =
request.getParameter("sid");
String nq_id =
request.getParameter("nqid");
if (userName == null) {
userName =
"mvdemo";
if (userPassword == null)
userPassword =
"mvdemo";
Document domDoc = null;
String fieldName = null;
String urlString =
"http://192.168.100.143:9704/analytics/saw.dll?Go&searchid=" +
thesid + "&format=xml&NQId=" + nq_id;
if (thesid != null) {
DocumentBuilderFactory
dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db =
dbf.newDocumentBuilder();
URL url = new URL(urlString);
URLConnection
URLconnection = url.openConnection();
HttpURLConnection
httpConnection = (HttpURLConnection)URLconnection;
int responseCode =
httpConnection.getResponseCode();
if ( responseCode ==
HttpURLConnection.HTTP_OK) {
InputStream in =
httpConnection.getInputStream();
System.out.println("thesid=
" + thesid);
System.out.println("nq_id="
+ nq_id);
System.out.println("server
host=" + request.getRemoteHost());
System.out.println("server
addr=" + request.getRemoteAddr());
domDoc = db.parse(in);
} else {
System.out.println(
"HTTP connection response != HTTP_OK" );
out.println("<nsdp_xml>");
out.println("<table>");
//Iterate
through metadata object and create the ndsp_xml header
NodeList rowDef =
domDoc.getElementsByTagName("element");
out.println("<tr>");
out.println("<th>Column
1</th><th>Column 2</th>");
out.println("</tr>");
//Iterate
through rows & items and create the ndsp_xml body
NodeList rows =
domDoc.getElementsByTagName("R");
if (rows != null) {
for (int i = 0; i <
rows.getLength(); i++) {
out.println("<tr>");
Node row = rows.item(i);
if (row == null ||
row.getNodeType() == Node.TEXT_NODE) {
continue;
NodeList items =
row.getChildNodes();
if (items == null) {
continue;
for (int y = 0; y < 2;
y++) {
Node item =
items.item(y);
if (item == null ||
item.getChildNodes() == null)
continue;
if (item.getChildNodes()
== null
||
item.getChildNodes().item(0) == null
|| item.getNodeType()
== Node.TEXT_NODE)
continue;
out.println("<td>"
+
item.getChildNodes().item(0).getNodeValue()
+ "</td>");
out.println("</tr>");
} else {
out.println("No
rows.");
out.println("</table>");
out.println("</nsdp_xml>");
%>
*3- Where the source Code of map I created on HTML : BIMapPage.html*
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html;
charset=windows-1252"></meta>
<title>BI Map
Page</title>
<script
language="Javascript" src="oraclemaps.js"></script>
<script
language="Javascript">
var dynStatesFOI;
function show_map(){
var map;
var homeCenter,
homeZoomLevel;
var baseURL =
"http://192.168.100.143:9704/mapviewer";
map = new
MVMapView(document.getElementById("map"), baseURL);
var mapSRID = 82364;
var mapCenterLon = 538940.5;
var mapCenterLat = 2690457.4;
homeZoomLevel = 1;
homeCenter =
MVSdoGeometry.createPoint(mapCenterLon, mapCenterLat, mapSRID);
map.addMapTileLayer(new MVMapTileLayer("tcg_gis.ksa_map"));
map.setCenter(homeCenter, false);
map.setZoomLevel(homeZoomLevel);
map.setHomeMap(homeCenter, homeZoomLevel);
map.addNavigationPanel("East");
map.addScaleBar();
dynStatesFOI = new
MVThemeBasedFOI('dynStatesFOI','tcg_gis.KSA_POP2');
dynStatesFOI.setRenderingStyle("C.COUNTIES");
setupNsdp(dynStatesFOI);
setupDynamicStyles(dynStatesFOI,250000,
500000, 750000);
map.addThemeBasedFOI(dynStatesFOI);
map.display();
function setupNsdp(dynStatesFOI)
var nsdpInfo = new
MVNSDP("defaultNSDP");
nsdpInfo.setTheme("KSA_POP2"); //the base theme
nsdpInfo.setKeyColumn("REGION_NAME");
//'match' column in the base table of the theme
nsdpInfo.setRenderStyle("C.COUNTIES"); //default style;
var ps = new Object();
{color:#ff0000}
ps["xml_url"] ="http://192.168.100.143/mapviewer/obiee_nsdp_xml_direct.jsp?nqid=" + urlParamNQID
+ "&sid=" + urlParamSID;{color} *{color:#800000}// <== Error line {color}*
nsdpInfo.setParameters(ps);
dynStatesFOI.setNSDP(nsdpInfo);
//setups the dynamically created advanced
style to
//be used by the theme-based FOI.
function setupDynamicStyles(dynStt,val1, val2, val3)
var buckets = new
Array(4);
buckets[0] = new
MVNumericRangedBucket(100000, val1, "C.COLOR_BLUE",
"range1");
buckets[1] = new
MVNumericRangedBucket(val1, val2, "C.COLOR_GREEN", "range2");
buckets[2] = new
MVNumericRangedBucket(val2, val3, "C.COLOR_RED", "range3");
buckets[3] = new
MVNumericRangedBucket(val3, null, "C.COLOR_BROWN",
"range4");
var bseries = new
MVBucketSeries("SCHEME_CUSTOM");
bseries.setBuckets(buckets);
var bucketSty = new
MVBucketStyle("region_colors", bseries);
dynStt.addStyle(bucketSty);
dynStt.setRenderingStyle("region_colors");
</script>
</head>
<body
onload="javascript:show_map();">
Welcome to our Site
Kingdom of Saudi Arabia
Map
<div
id="map"
style="width:550.0px; height:500.0px; overflow:auto;
border-color:rgb(0,0,0);"/>
</body>
</html>
{color:#ff0000}
The
highlighted line above from function setupNSDP is code line for: NSDP xml
source to call jsp that invokes java class to convert Answers filtered XML (OBIEE)
into NSDP XML.
Where
its invoke two parameters : 1- urlParamNQID , 2- urlParamSID
ps["xml_url"] =
"http://192.168.100.143/mapviewer/obiee_nsdp_xml_direct.jsp?nqid="
+ urlParamNQID + "&sid=" + urlParamSID;
The
error when we run this code is: URLParamNQID is not defined ???
does any of you can read what i wrote in my source codes and let me know what i missed in my html map code : BIMapPage.html and where or how i can get two parameters values URLParamNQID
and {color}*{color:#ff0000}urlParamSID{color}*{color:#ff0000}?{color}yes i checked this site, but i still couldn't reach the answer of my challenge, in how to specify urlParamNQID and urlParamSID , how or where i can get value of these parameters or what should i pass there !?
-
HTTP POST to PHP server problem
Hi, im trying post a long string to php from a MIDLET, but i have some problems. When i send the whole String, my php server cant receive the request (i have not any response), but, if the string that i send is 1/5 from the original, the process is successful correctly. have somebody any idea?
thxthis is my problem, extracted from another topic on this forum:
"Hi everyone.
I have a problem, and hope someone may help me.
My midlet is uploading sizeable data via http POST.
I'm using WTK104, since i need MIDP1.0
The code have been tried on DefaultGrayPhone emulator
and add-on Nokia's Series 60 Emulator.
Both emulators chunck data, however in different ways.
Deafult one simply produces wrong chunk length (possibly a bug),
Nokia's one always chunks by equal offsets of 2016 bytes.
I'm not using flushing, just close. All the data is being send
at once by one output stream write call.
So I believe (after proper investigation) that MIDP will use chunked Transfer-Encoding method whatever
on such sizeable a data as mine is (up to 50KB) and there's no way to override this behaviour.
Here the main problem appears - Apache refuses to accept chunked encoding in request. The corresposnding message is given in error log
*chunked transfer encoding forbidden*. The returned code is 411 - Content-Length requred. I see no way to override this behaviour of Apache. I was trying to upload my data into Zope web-server, which is my primary goal, but it doesn't handle chunked request either.
Has anyone faced the same problem? Who has managed to POST sizeable data from midlet? Which web servers did you use for that?
Any inputs are highly appreciated!
Anton"
Another:
"> So I believe (after proper investigation) that MIDP
will use chunked Transfer-Encoding method whatever
on such sizeable a data as mine is (up to 50KB) and
there's no way to override this behaviour.Is this true? When I try to set the content-length headers and then write a large byte[] to the output stream I got from an HttpConnection, the HttpConnection appears to remove the content-length header altogether and automatically sets the transfer-encoding to chunked.
Note- I am not calling flush on the outputstream, but I am calling httpconnection.getResponseCode, which I believe calls flush on the outputstream.
Abraham"
I have the identical problem. -
Hello all,
I am attempting to write a basic link checker to parse an html page and determine if any links are dead. I found a couple tutorials online, and am using one of them to test a webpage. However, i am running into multiple problems. The basic link checker verifies links by using the http HEAD request, it then checks the response code and determines from there if the link is dead.
However, I have two major problems with this:
1) How can I verify links when they are not using http, for instance a ftp link on a webpage?
2) Sometimes when I parse link, i am losing the protocol from the link....
ie. href="http://www.ibm.com/systems/x/=>href="//www.ibm.com/systems/x/"
Reader rd = getReader(rootURI);
// Parse the HTML.
kit.read(rd, doc, 0);
// Iterate through the elements
// of the HTML document.
ElementIterator it = new ElementIterator(doc);
javax.swing.text.Element elem;
System.out.println("Starting Validation from: " + rootURI);
while ((elem = it.next()) != null) {
SimpleAttributeSet s = (SimpleAttributeSet)elem.getAttributes().getAttribute(HTML.Tag.A);
if (s != null) {
System.out.println("attributeSet: " + s);
String link = (String)s.getAttribute(HTML.Attribute.HREF);
System.out.println("Validating: " + link);
validateHref(link);
}else{
//System.out.println("Attribute set is empty");
//flag this to user
}This is the block of code i am using to extract the link from the html source. My console output looks like this:
[stdout]
attributeSet: href=//www.ibm.com/systems/x/ class=left-nav-overview
Validating: //www.ibm.com/systems/x/
[stdout]
However, looking at the html source, the link should be http protocol....ie. http://www.ibm.com/systems/x , since i later check to make sure that http protocal urls start with "http:", these links that do not have http: at the beginning are being ignored...
Can someone please help and explain to me how I can fix this? Also, i am eventually planning to turn this into more of a web spider, and traverse levels of pages checking and validating the links.
Thank you,
Nickheres the full source. Let me know if theres anything else to make my questions more clear. Thanks!
import java.io.*;
import java.net.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
public class enhanceLinkCheck {
static int failCnt = 0;
public static void main(String[] args) {
HttpURLConnection.setFollowRedirects(false);
EditorKit kit = new HTMLEditorKit();
Document doc = kit.createDefaultDocument();
// The Document class does not yet
// handle charset's properly.
doc.putProperty("IgnoreCharsetDirective",
Boolean.TRUE);
try{
//String rootURI = "http://www-304.ibm.com/jct01004c/systems/support/supportsite.wss/docdisplay?lndocid=MIGR-65651&brandind=5000008#osa";
String rootURI = "http://www-304.ibm.com/jct01004c/systems/support/supportsite.wss/docdisplay?lndocid=MIGR-65665&brandind=5000008";
// Create a reader on the HTML content.
Reader rd = getReader(rootURI);
// Parse the HTML.
kit.read(rd, doc, 0);
// Iterate through the elements
// of the HTML document.
ElementIterator it = new ElementIterator(doc);
javax.swing.text.Element elem;
System.out.println("Starting Validation from: " + rootURI);
while ((elem = it.next()) != null) {
SimpleAttributeSet s = (SimpleAttributeSet)elem.getAttributes().getAttribute(HTML.Tag.A);
if (s != null) {
System.out.println("attributeSet: " + s);
String link = (String)s.getAttribute(HTML.Attribute.HREF);
System.out.println("Validating: " + link);
validateHref(link);
}else{
//System.out.println("Attribute set is empty");
}catch (Exception e){
e.printStackTrace();
System.out.println("Failed links: " + failCnt);
System.exit(1);
// Returns a reader on the HTML data. If 'uri' begins
// with "http:", it's treated as a URL; otherwise,
// it's assumed to be a local filename.
static Reader getReader(String uri)
throws IOException {
if (uri.startsWith("http:")) {
// Retrieve from Internet.
URLConnection conn = new URL(uri).openConnection();
return new InputStreamReader(conn.getInputStream());
}else {
// Retrieve from file.
return new FileReader(uri);
private static void validateHref(String urlString){
if((urlString != null) && (urlString.startsWith("http://"))){
try{
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
if(connection instanceof HttpURLConnection){
HttpURLConnection httpConnection = (HttpURLConnection)connection;
httpConnection.setRequestMethod("HEAD");
httpConnection.connect();
int response = httpConnection.getResponseCode();
if(response >=400){
System.out.print("[FAILED]");
failCnt++;
System.out.println("Response: " + response);
String location = httpConnection.getHeaderField("Location");
if(location != null){
System.out.println("Location: " + location);
System.out.println();
}else {
System.out.println("Connection not HTTP: " + connection);
}catch (IOException e){
e.printStackTrace();
} -
Connect/Socket Timedout Exception is not thrown
Hi,
I am getting the following problem very often. when I tried to connect to some URLs I am not able to connect those URLs and they didnot thrown any exceptions also but the process will be running until we kill explictly. here is my code
URL url = null;
String redirectUrl=null;
HttpURLConnection.setFollowRedirects(true);
URLConnection connection=null;
HttpURLConnection httpConnection=null;
String urlString = inpuUrl;
try {
url = new URL(urlString);
connection = url.openConnection();
connection.setConnectTimeout(30000);
if (connection instanceof HttpURLConnection) {
httpConnection = (HttpURLConnection) connection;
httpConnection.connect();
int response = httpConnection.getResponseCode();
url = httpConnection.getURL();
redirectUrl= url.getHost();
} catch (UnknownHostException eh) {
log.error(eh.getMessage(), eh);
} catch (ConnectException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
} catch (IllegalArgumentException e) {
log.error(e.getMessage(), e);
} catch (Exception e) {
log.error(e.getMessage(), e);
}please help me out how can I comeout from this, I want the redirected url of the input url. if it is not able to establish the connection then it shoud return null but the itis not return any thinn and the process is going to sleep mode
wating for reply.
BhaskarO/R mappers such as Hibernate and JDO generally defer communications with the database for as long as possible; for an insert or update transaction that will be until commit().
This is for several reasons:
1) general efficiency - a series of update() calls may modify the same attribute of an object multiple times; it's substantially more efficient to update the database just once
2) database efficiency - when a transaction is in progress, even when nothing is occuring in that transaction, more resources are consumed inthe database than when no transaction is active. For example, if a transaction updates a row and then 10 minutes later commits, then during that interval the database has to keep track of 2 different versions of that row and know which connections see which version of the row.
3) connection management - DB connections are expensive resources and once a transaction has started updating the DB, it has to tie up a connection for the duration.
In other words, no matter how long it takes to set up your transaction in Java, a good O/R mapper is not going to begin a database transaction until the last possible moment, which is at commit().
Can I force it to throw immediatelyYou can call commit() any time you want.
It sounds like you want the database to do your input data validation for you. That's wrong. You need to validate input (for size, length, whatever) before you attempt to put it in the database. -
Response code is always returnd as -1
url = new URL(urlString);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
httpConnection.getHeaderFields();
int responsecode = httpConnection.getResponseCode();
if (responsecode == HttpURLConnection.HTTP_NOT_MODIFIED) {
....//fetch from cache
else {
....// save to cache
}In the above snippet the responsecode is always returned as -1. But the data returned in the response is properly read. Also the headers are shown null. But they are getting saved.
On checking with TCP tool, I found that the server is actually returning the response code and headers properly.
Am I missing any configuration or setting?I don't know that you've actually obtained an HTTP response at that point: maybe you are getting the initial value. I would do some I/O or get an actual header value before trying the response code.
Maybe you are looking for
-
How do I rid my iTunes library of duplicates and broken links?
How do I rid my iTunes library of duplicates and broken links?
-
Manipulating SOAP message in Servlet Filter
I need to capture the client IP address and place it in the SOAP message to pass it to the underlying EJB. I am using a servlet filter to capture the IP Address but dont really know how to get the SOAP message from the HTTPServletRequest. Any clues ?
-
My still photos won't all show in my movie
My movie has both still images and video. However, i movie gets stuck on the previous video clip in playback and the sequence of still photos won't appear. I've not had this problem before. Any ideas? Thanks
-
Comparing documents in Pages?
Hello, How do I compare 2 versions of a word document in Pages to see the differences? (Alternatively, is there any way to do this using the terminal?) Please help! Thanks in advance! Lali
-
AIR 2.7.1: Help with sound stuttering problem in IOS!
Hi all, I need to play audio in the background but unfortunately, it came out unstable: - On the 1st run after installing, it'll play fine until it loops, that's when the audio goes out completely. - On subsequent runs, the audio plays and loops but