private Image getAvatar() { HttpConnection httemp = null; InputStream istemp = null; Image avatar = null; try { httemp = (HttpConnection) Connector.open(url); if (HttpConnection.HTTP_OK != httemp.getResponseCode()) { throw new IOException(); } istemp = httemp.openInputStream(); byte[] avatarBytes = read(istemp, (int) httemp.getLength()); // #sijapp cond.if modules_TRAFFIC is "true" # Traffic.getInstance().addInTraffic(avatarBytes.length); // #sijapp cond.end# avatar = javax.microedition.lcdui.Image.createImage(avatarBytes, 0, avatarBytes.length); avatarBytes = null; } catch (Exception e) { } try { httemp.close(); istemp.close(); } catch (Exception e) { } return avatar; }
public static EncodedImage getImage(String url, Manager parent) throws IOException { url += ";deviceside=true"; HttpConnection connection = null; InputStream inputStream = null; try { ConnectionFactory cf = new ConnectionFactory(); cf.setConnectionTimeout(2500); ConnectionDescriptor cd = cf.getConnection(url); HttpConnection httpConn; httpConn = (HttpConnection) cd.getConnection(); inputStream = httpConn.openInputStream(); StringBuffer rawResponse = new StringBuffer(); byte[] responseData = new byte[10000]; int length = 0; while (-1 != (length = inputStream.read(responseData))) { rawResponse.append(new String(responseData, 0, length)); } String result = rawResponse.toString(); byte[] dataArray = result.getBytes(); // Image.createImage(InputStream); httpConn.close(); return EncodedImage.createEncodedImage(dataArray, 0, dataArray.length); } catch (IOException e1) { // } return null; }
public void close() throws IOException { try { is.close(); } finally { connection.close(); } }
private int availableMessages() { String content; try { StreamConnection s = null; s = (StreamConnection) Connector.open(getAvailableUrl()); HttpConnection httpConn = (HttpConnection) s; int status = httpConn.getResponseCode(); if (status == HttpConnection.HTTP_OK) { // Is this html? InputStream input = s.openInputStream(); byte[] data = new byte[256]; int len = 0; int size = 0; StringBuffer raw = new StringBuffer(); while (-1 != (len = input.read(data))) { // Exit condition for the thread. An IOException is // thrown because of the call to httpConn.close(), // causing the thread to terminate. if (_stop) { httpConn.close(); s.close(); input.close(); } raw.append(new String(data, 0, len)); size += len; } // raw.insert(0, "bytes received]\n"); // raw.insert(0, size); // raw.insert(0, '['); content = raw.toString(); input.close(); } else { content = "response code = " + status; } s.close(); } catch (IOCancelledException e) { System.out.println(e.toString()); return inserted; } catch (Exception e) { System.out.println(e.toString()); return inserted; } String intString = content; int i = 0; for (; i < content.length(); i++) { char aChar = content.charAt(i); if (aChar < '0' || aChar > '9') break; } if (i > 0) return Integer.parseInt(content.substring(0, i)); return inserted; }
public void close() throws IOException { if (is != null) { is.close(); is = null; } if (os != null) { os.close(); os = null; } httpConnection.close(); }
private Object request( String url, boolean post, Hashtable params, boolean basicAuth, boolean processOutput) throws Exception { HttpConnection conn = null; Writer writer = null; InputStream is = null; try { if (!post && (params != null)) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(baos, this.encoding); this.encodeParams(params, osw); osw.flush(); osw.close(); osw = null; url += "?" + new String(baos.toByteArray(), this.encoding); baos = null; } conn = (HttpConnection) Connector.open(url); conn.setRequestMethod(post ? HttpConnection.POST : HttpConnection.GET); if (basicAuth) { if (!this.areCredentialsSet()) throw new Exception("Credentials are not set"); String token = base64Encode((this.user + ":" + this.pass).getBytes(this.encoding)); conn.setRequestProperty("Authorization", "Basic " + token); } if (post && (params != null)) { OutputStream os = conn.openOutputStream(); writer = new OutputStreamWriter(os, this.encoding); this.encodeParams(params, writer); writer.flush(); writer.close(); os = null; writer = null; } int code = conn.getResponseCode(); if ((code != 200) && (code != 302)) throw new Exception("Unexpected response code " + code + ": " + conn.getResponseMessage()); is = conn.openInputStream(); if (processOutput) { synchronized (this.json) { return this.json.parse(is); } } else { this.pump(is, System.out, 1024); return null; } } finally { if (writer != null) writer.close(); if (is != null) is.close(); if (conn != null) conn.close(); } }
private String getContent(String url) { HttpConnection httemp = null; InputStream istemp = null; String content = ""; try { httemp = (HttpConnection) Connector.open(url); httemp.setRequestProperty("Connection", "cl" + "ose"); if (HttpConnection.HTTP_OK != httemp.getResponseCode()) { throw new IOException(); } istemp = httemp.openInputStream(); int length = (int) httemp.getLength(); if (-1 != length) { byte[] bytes = new byte[length]; istemp.read(bytes); content = new String(bytes); } else { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); while (true) { int ch = istemp.read(); if (-1 == ch) break; bytes.write(ch); } content = new String(bytes.toByteArray()); bytes.close(); } } catch (Exception e) { content = "Error: " + e.getMessage(); } try { httemp.close(); istemp.close(); } catch (Exception e) { } return StringConvertor.removeCr(content); }
/** * Processes a new HttpConnection object to instantiate a new browser Field (aka WebView) object, * and then resets the screen to the newly-created Field. * * @param connection * @param e */ public void processConnection(HttpConnection connection, Event e) { // Cancel previous request. if (_currentConnection != null) { try { _currentConnection.close(); } catch (IOException e1) { } } // Clear out pending responses. synchronized (pendingResponses) { pendingResponses.removeAllElements(); } // Cancel any XHRs happening. commandManager.stopXHR(); _currentConnection = connection; BrowserContent browserContent = null; Field field = null; try { browserContent = _renderingSession.getBrowserContent(connection, this, e); if (browserContent != null) { field = browserContent.getDisplayableContent(); if (field != null) { synchronized (Application.getEventLock()) { _mainScreen.deleteAll(); _mainScreen.add(field); } } browserContent.finishLoading(); } } catch (RenderingException re) { } finally { browserContent = null; field = null; // Manually call the garbage collector to clean up all of leftover objects and free up the // nulled object handles. System.gc(); } }
/** * Gets the connection attribute of the CommonDS object * * @exception IOException Description of the Exception */ void getConnection() throws IOException { boolean goodurl = false; if (locator == null) { throw (new IOException(this + ": connect() failed")); } contentType = null; String fileName = getRemainder(locator); if (fileName == null) { throw new IOException("bad url"); } int i = fileName.lastIndexOf((int) ('.')); if (i != -1) { String ext = fileName.substring(i + 1).toLowerCase(); contentType = Configuration.getConfiguration().ext2Mime(ext); } if (contentType == null) { contentType = "unknown"; } try { if (locator.toLowerCase().startsWith("http:")) { HttpConnection httpCon = (HttpConnection) Connector.open(locator); int rescode = httpCon.getResponseCode(); // If the response code of HttpConnection is in the range of // 4XX and 5XX, that means the connection failed. if (rescode >= 400) { httpCon.close(); goodurl = false; } else { inputStream = httpCon.openInputStream(); contentLength = httpCon.getLength(); String ct = httpCon.getType().toLowerCase(); if (contentType.equals("unknown")) { contentType = Configuration.getConfiguration().ext2Mime(ct); } httpCon.close(); goodurl = true; } } else if (locator.startsWith("file:")) { // #ifdef USE_FILE_CONNECTION [ FileConnection fileCon = (FileConnection) Connector.open(locator); if (fileCon.exists() && !fileCon.isDirectory() && fileCon.canRead()) { inputStream = fileCon.openInputStream(); contentLength = fileCon.fileSize(); fileCon.close(); goodurl = true; } else { fileCon.close(); goodurl = false; } // #else ] [ // throw new IOException("file protocol isn't supported"); // #endif ] } else if (locator.startsWith("rtp:")) { if (contentType.equals("unknown")) contentType = "content.rtp"; inputStream = null; contentLength = -1; goodurl = true; } else if (locator.startsWith("rtsp:")) { if (contentType.equals("unknown")) contentType = "content.rtp"; inputStream = null; contentLength = -1; goodurl = true; } else if (locator.equals(Manager.TONE_DEVICE_LOCATOR) // #ifndef ABB [ // || locator.equals(Manager.MIDI_DEVICE_LOCATOR) // #endif ] ) { inputStream = null; contentLength = -1; goodurl = true; } } catch (Exception ex) { ex.printStackTrace(); throw new IOException("failed to connect: " + ex.getMessage()); } if (!goodurl) throw new IOException("bad url"); }
private String postViaHttpConnection(String url, byte[] b) throws IOException { HttpConnection c = null; InputStream is = null; OutputStream os = null; int rc; try { c = (HttpConnection) Connector.open(url); // Set the request method and headers c.setRequestMethod(HttpConnection.POST); c.setRequestProperty("If-Modified-Since", "29 Oct 1999 19:43:31 GMT"); c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0"); c.setRequestProperty("Content-Language", "en-US"); // Getting the output stream may flush the headers os = c.openOutputStream(); os.write(b); os.flush(); // Optional, getResponseCode will flush // Getting the response code will open the connection, // send the request, and read the HTTP response headers. // The headers are stored until requested. rc = c.getResponseCode(); if (rc != HttpConnection.HTTP_OK) { throw new IOException("HTTP response code: " + rc); } is = c.openInputStream(); // Get the ContentType String type = c.getType(); // processType(type); // Get the length and process the data int len = (int) c.getLength(); if (len > 0) { int actual = 0; int bytesread = 0; byte[] data = new byte[len]; while ((bytesread != len) && (actual != -1)) { actual = is.read(data, bytesread, len - bytesread); bytesread += actual; } String s = ""; for (int i = 0; i < data.length; i++) { s = s + (char) data[i]; } return s; } // else { // int ch; // while ((ch = is.read()) != -1) { // process((byte)ch); // } // } } catch (ClassCastException e) { throw new IllegalArgumentException("Not an HTTP URL"); } finally { if (is != null) is.close(); if (os != null) os.close(); if (c != null) c.close(); } return "Resp"; // }
private synchronized void httpPostRequest(String postData) throws IOException { try { HttpConnection hc = (HttpConnection) Connector.open(pollingUrl); hc.setRequestMethod(HttpConnection.POST); hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); hc.setRequestProperty("Host", "host"); StringBuffer out = new StringBuffer(); if (sessionId == null) { out.append("0"); keys = new Vector(); } else out.append(sessionId); do { if (keys.size() == 0) { initKeys(); } out.append(";").append((String) keys.lastElement()); keys.removeElementAt(keys.size() - 1); } while (keys.size() == 0); out.append(",").append(postData); int outLen = out.length(); // hc.setRequestProperty("Content-Length", String.valueOf(outLen)); byte bytes[] = new byte[outLen]; for (int i = 0; i < outLen; i++) { bytes[i] = (byte) out.charAt(i); } OutputStream os = hc.openOutputStream(); os.write(bytes); os.close(); int resp = hc.getResponseCode(); if (resp != HttpConnection.HTTP_OK) throw new IOException("HTTP Error code" + resp); InputStream is = hc.openInputStream(); String cookie = hc.getHeaderField("Set-Cookie"); int expires = cookie.indexOf(';'); if (expires > 0) cookie = cookie.substring(3, expires); if (cookie.endsWith(":0")) { opened = false; error = cookie; } if (sessionId == null) { sessionId = cookie; } byte data[]; int inLen = (int) hc.getLength(); if (inLen < 0) { throw new Exception("Content-Length missing"); // TODO: } else { int actual = 0; int bytesread = 0; data = new byte[inLen]; while ((bytesread != inLen) && (actual != -1)) { actual = is.read(data, bytesread, inLen - bytesread); bytesread += actual; } if (inLen > 0) inStack.addElement(data); } is.close(); hc.close(); } catch (Exception e) { opened = false; error = e.toString(); // #ifdef DEBUG // # e.printStackTrace(); // #endif } }
/** * Invokes the wsdl:operation defined by this <code>Operation</code> and returns the result. * * @param params a <code>ValueType</code> array representing the input parameters for this <code> * Operation</code>. Can be <code>null</code> if this operation takes no parameters. * @return a <code>ValueType</code> array representing the output value(s) for this operation. Can * be <code>null</code> if this operation returns no value. * @throws JAXRPCException * <UL> * <LI>if an error occurs while excuting the operation. * </UL> * * @see javax.microedition.xml.rpc.Operation */ public Object invoke(Object params) throws JAXRPCException { HttpConnection http = null; OutputStream ostream = null; InputStream istream = null; Object result = null; int attempts = 0; // Maximal number of "Object moved" http responses that we will handle final int maxAttempts = 10; // Constants.MAX_REDIRECT_ATTEMPTS; try { do { // This flag will be set to 'true' by setupResStream() method // if code 3xx is returned by the http connection. resourceMoved = false; // open stream to service endpoint http = (HttpConnection) Connector.open(getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY)); ostream = setupReqStream(http); // IMPL NOTE: encoding should be either UTF-8 or UTF-16 encoder.encode(params, inputType, ostream, null); if (ostream != null) { ostream.close(); } istream = setupResStream(http); if (returnType != null && istream != null) { result = decoder.decode(returnType, istream, http.getEncoding(), http.getLength()); } if (http != null) { http.close(); } if (istream != null) { istream.close(); } } while (resourceMoved && (attempts++ < maxAttempts)); if (resourceMoved) { throw new JAXRPCException("Too many redirections"); } return result; } catch (Throwable t) { // Debug Line if (ostream != null) { try { ostream.close(); } catch (Throwable t2) { } } if (istream != null) { try { istream.close(); } catch (Throwable t3) { } } if (http != null) { try { http.close(); } catch (Throwable t1) { } } // Re-throw whatever error/exception occurs as a new // JAXRPCException if (t instanceof JAXRPCException) { throw (JAXRPCException) t; } else { if (t instanceof MarshalException || t instanceof ServerException || t instanceof FaultDetailException) { throw new JAXRPCException(t); } else { throw new JAXRPCException(t.toString()); } } } }
public void run() { if (URL != null && URL.length() > 0) { ConnectionFactory f = new ConnectionFactory(); ConnectionDescriptor descr = f.getConnection(URL); String targetURL; targetURL = descr.getUrl(); HttpConnection httpConnection = null; DataOutputStream httpDataOutput = null; InputStream httpInput = null; int rc; try { httpConnection = (HttpConnection) Connector.open(targetURL); rc = httpConnection.getResponseCode(); if (rc != HttpConnection.HTTP_OK) { throw new IOException("HTTP response code: " + rc); } httpInput = httpConnection.openInputStream(); InputStream inp = httpInput; byte[] b = IOUtilities.streamToBytes(inp); final EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length); final Bitmap bmp = hai.getBitmap(); System.out.println(bmp.toString()); if (target != null) { UiApplication.getUiApplication() .invokeLater( new Runnable() { public void run() { // TODO Auto-generated method stub if (isDetailEvent == true) { target.setBitmap( DisplayHelper.CreateScaledCopyKeepAspectRatio( bmp, (int) (Display.getWidth() * 0.7), (int) (Display.getHeight() * 0.3))); } else { target.setBitmap( DisplayHelper.CreateScaledCopyKeepAspectRatio( bmp, target.getBitmapWidth(), target.getBitmapHeight())); } } }); } if (localPath != null) { Utils.saveBitmap(localPath, bmp); } if (imageCache != null) { if (Utils.saveBitmap( ImageCacheModel.getImageCacheDirectory() + imageCache.getFileName(), bmp)) { // CacheUtils.getInstance().addImageCache(imageCache); System.out.println("image write success"); } } if (callback != null) callback.onImageDownloaded(true, bmp); } catch (Exception ex) { System.out.println("URL Bitmap Error........" + ex.getMessage()); } finally { try { if (httpInput != null) httpInput.close(); if (httpDataOutput != null) httpDataOutput.close(); if (httpConnection != null) httpConnection.close(); } catch (Exception e) { e.printStackTrace(); } } } }
public int postViaHttpConnection(String url) { // throws IOException, // RecordStoreException { HttpConnection c = null; InputStream is = null; OutputStream os = null; int rc = -1; int recID = 0; RecordEnumeration recIter = null; SigSeg sigSeg = null; this.log("Test1"); try { try { c = (HttpConnection) Connector.open(url, Connector.READ_WRITE); } catch (IllegalArgumentException e) { this.alertError("post:open IllegalArgument: parameter is invalid. " + e.getMessage()); throw e; } catch (ConnectionNotFoundException e) { this.alertError( "post:open ConnectionNotFound: target not found, or protocol not supported. " + e.getMessage()); throw e; } catch (IOException e) { this.alertError("post:open IOException: " + e.getMessage()); throw e; } catch (SecurityException e) { this.alertError("post:open SecurityException: " + e.getMessage()); throw e; } this.log("Test2"); try { c.setRequestMethod(HttpConnection.POST); } catch (IOException e) { this.alertError( "post:setReqMethod IOException: the method cannot be reset or if the requested method isn't valid for HTTP:" + e.getMessage()); throw e; } this.log("Test3"); try { c.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); c.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0"); c.setRequestProperty("Accept", "text/plain"); c.setRequestProperty("Accept-Encoding", "identity"); } catch (IOException e) { this.alertError( "post:setReqProperty IOException: connection is in connected state." + e.getMessage()); throw e; } this.log("Test4"); try { os = c.openOutputStream(); } catch (IOException e) { this.alertError( "post:openOutputStream IOException: maybe output stream has been closed?" + e.getMessage()); throw e; } this.log("Test5"); StringBuffer postBuf = new StringBuffer(); postBuf.append("email=adparker%40gmail.com"); postBuf.append("&pw=ecopda"); postBuf.append("&type=xml"); postBuf.append("&project_id=43"); postBuf.append("&tableName=test2"); postBuf.append("&data_string="); try { recIter = this.recordStore.enumerateRecords(null, null, true); } catch (RecordStoreNotOpenException e) { this.alertError("post:enumrateRecords RecordStoreNotOpenException" + e.getMessage()); throw e; } this.log("Test6"); try { recID = recIter.nextRecordId(); } catch (InvalidRecordIDException e) { this.alertError("post:nextRecordId: no more records." + e.getMessage()); throw e; } this.log("Test7"); try { sigSeg = new SigSeg(this.recordStore, recID); } catch (RecordStoreNotOpenException e) { alertError("post:SigSeg RecordStoreNotOpen "); // + // e.getMessage()); throw e; } catch (InvalidRecordIDException e) { alertError("post:SigSeg InvalidIDException "); // + // e.getMessage()); throw e; } catch (RecordStoreException e) { alertError("post:SigSeg RecordStoreException"); // ";//+ // e.getMessage());; throw e; } catch (IOException e) { alertError("post:SigSeg IOException " + e.getMessage()); throw e; } this.log("Test8"); postBuf.append(URLEncode.encode("<table>")); postBuf.append(URLEncode.encode("<row>")); // <field name="user">ASDFASDF</field> postBuf.append(URLEncode.encode("<field name=\"user\">")); String _userName = this.midlet.strItem_userName.getString(); postBuf.append(URLEncode.encode(_userName)); postBuf.append(URLEncode.encode("</field>")); postBuf.append(URLEncode.encode(sigSeg.toXML())); // postBuf.append(sigSeg.toXML()); // sigSeg.toXML(); postBuf.append(URLEncode.encode("</row>")); postBuf.append(URLEncode.encode("</table>")); // URL encode! try { // String urlenc = URLEncode.encode(postBuf.toString()); // String urlenc = postBuf.toString(); os.write(postBuf.toString().getBytes()); } catch (IOException e) { alertError("post:os.write IOException " + e.getMessage()); throw e; } this.log("Test9"); try { os.flush(); } catch (IOException e) { alertError("post:os.flush IOException " + e.getMessage()); throw e; } this.log("Test10"); try { rc = c.getResponseCode(); } catch (IOException e) { alertError("post:c.getResponseCode IOException" + e.getMessage()); throw e; } this.log("Test11"); if (rc != HttpConnection.HTTP_OK) { this.alertError("HTTP response code: " + String.valueOf(rc)); } else { ++this.int_recordsSent; } this.popRecord(recID); this.updateView(); } catch (Exception e) { } finally { if (is != null) try { is.close(); } catch (IOException e) { e.printStackTrace(); } if (os != null) try { os.close(); } catch (IOException e) { e.printStackTrace(); } if (c != null) try { c.close(); } catch (IOException e) { e.printStackTrace(); } } return rc; }
public String ReadRemoteFile() throws IOException { HttpConnection hc = null; // DataInputStream dis = null; InputStream is = null; ByteArrayOutputStream baos = null; byte[] data = null; String sResult = ""; StringBuffer sb = new StringBuffer(); int length = 0; try { // String local_code = ReadLocalCode("expe"); String local_code = "201101"; String url = sHttpSchema + sRemoteRoot + sLocalExpePrefix + local_code + sLocalDataExt; hc = (HttpConnection) Connector.open(url); hc.setRequestMethod(HttpConnection.GET); int iResponseCode = hc.getResponseCode(); if (iResponseCode == HttpConnection.HTTP_OK) { is = hc.openInputStream(); length = (int) hc.getLength(); if (length != -1) { data = new byte[length]; is.read(data); sResult = new String(data); } else { baos = new ByteArrayOutputStream(); int ch; while ((ch = is.read()) != -1) { baos.write(ch); } sResult = new String(baos.toByteArray()); } System.out.println(sResult); } else { sResult = "ERROR: NO iResponseCode == HttpConnection.HTTP_OK"; System.out.println(sResult); } /*if (length != -1) { data = new byte[length]; dis = new DataInputStream(hc.openInputStream()); //dis.readFully(data); } else { SetMessages("ERROR: Content length not given."); }*/ /*int ch; while ((ch = is.read()) != -1) { sb.append((char) ch); }*/ // sResult = sb.toString(); // System.out.println(sResult); } catch (ConnectionNotFoundException cnfex) { SetMessages(cnfex.toString()); sResult = GetMessages(); cnfex.printStackTrace(); } catch (IOException ioex) { SetMessages(ioex.toString()); sResult = GetMessages(); ioex.printStackTrace(); } catch (Exception ex) { SetMessages(ex.toString()); sResult = GetMessages(); ex.printStackTrace(); } finally { if (baos != null) { baos.close(); } if (is != null) { is.close(); } if (hc != null) { hc.close(); } } return sResult; }
public SearchProductoCx(int idcategoria, String PalabraFiltro) { SearchProductoSG searchproducto = new SearchProductoSG(); try { connectionURL = Strings.HTTP_SW + "getListaDeProductosPorCategoriaPorNombre/" + idcategoria + "/" + PalabraFiltro + tipoConexion; conn = (HttpConnection) Connector.open(connectionURL); conn.setRequestProperty("Content-Type", "application/json"); // System.out.println("Response code : "+conn.getResponseCode()); if (conn.getResponseCode() == HttpConnection.HTTP_OK) { is = conn.openInputStream(); int ch = -1; bos = new ByteArrayOutputStream(); while ((ch = is.read()) != -1) { bos.write(ch); } response = new String(bos.toByteArray(), "UTF-8"); JSONObject objeto1 = new JSONObject(response); String resultado1 = objeto1.getString("response"); JSONObject objeto2 = new JSONObject(resultado1); errorCode = objeto2.getString("errorCode"); errorMessage = objeto2.getString("errorMessage"); JSONArray jsonMainArr = objeto2.getJSONArray("msg"); for (int i = 0; i < jsonMainArr.length(); i++) { JSONObject childJSONObject = jsonMainArr.getJSONObject(i); IdProducto.addElement(childJSONObject.get("idProducto")); Nombre.addElement(childJSONObject.get("nombre")); } } } catch (Exception e) { // TODO: handle exception } finally { if (conn != null) try { conn.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (is != null) try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } searchproducto.setIdProducto(IdProducto); searchproducto.setNombre(Nombre); searchproducto.seterrorCode(errorCode); searchproducto.seterrorMessage(errorMessage); }
public void descargarDatos() { try { connectionURL = Strings.HTTP_SW + "getMunicipios/" + tipoConexion; // Dialog.alert(connectionURL+"<<URL"); conn = (HttpConnection) Connector.open(connectionURL); conn.setRequestProperty("Content-Type", "application/json"); // System.out.println("Response code : "+conn.getResponseCode()); if (conn.getResponseCode() == HttpConnection.HTTP_OK) { is = conn.openInputStream(); int ch = -1; bos = new ByteArrayOutputStream(); while ((ch = is.read()) != -1) { bos.write(ch); } response = new String(bos.toByteArray(), "UTF-8"); // JSONObject temporalError = new JSONObject ( response ); // errorCode = temporalError.getString("errotCode"); // errorMessage = temporalError.getString("errorMessage"); JSONObject objeto1 = new JSONObject(response); String resultado1 = objeto1.getString("response"); // Dialog.alert(resultado1+"<<"); JSONObject objeto2 = new JSONObject(resultado1); errorCode = objeto2.getString("errorCode"); errorMessage = objeto2.getString("errorMessage"); if (errorCode.equals("0")) { JSONArray jsonMainArr = objeto2.getJSONArray("msg"); for (int i = 0; i < jsonMainArr.length(); i++) { JSONObject childJSONObject = jsonMainArr.getJSONObject(i); IdMunicipio.addElement(childJSONObject.get("idMunicipio")); NombreMunicipio.addElement(childJSONObject.get("municipio")); } } else if (errorCode.equals("1")) { if (Display.getWidth() == 320) { errorMessage = "noData1_320.png"; } if (Display.getWidth() == 360) { errorMessage = "noData1_360.png"; } if (Display.getWidth() == 480) { errorMessage = "noData1_480.png"; } if (Display.getWidth() == 640) { errorMessage = "noData1.png"; } } } } catch (Exception e) { // TODO: handle exception if (Display.getWidth() == 320) { errorMessage = "noData1_320.png"; } if (Display.getWidth() == 360) { errorMessage = "noData1_360.png"; } if (Display.getWidth() == 480) { errorMessage = "noData1_480.png"; } if (Display.getWidth() == 640) { errorMessage = "noData1.png"; } } finally { if (conn != null) try { conn.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (is != null) try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } municipiocompras.setIdMunicipio(IdMunicipio); municipiocompras.setNombreMunicipio(NombreMunicipio); municipiocompras.seterrorCode(errorCode); municipiocompras.seterrorMessage(errorMessage); }
String postRequest(String url) { HttpConnection hc = null; DataInputStream in = null; OutputStream os = null; try { hc = (HttpConnection) Connector.open(url); hc.setRequestMethod(HttpConnection.POST); hc.setRequestProperty("username", "bng"); hc.setRequestProperty("password", "123456"); os = hc.openDataOutputStream(); JSONObject jSONObject = new JSONObject(); jSONObject.put("start_count", 1); jSONObject.put("end_count", 10); jSONObject.put("type", 1); // os.write("{\"start_count\":\"1\",\"end_count\":\"12\"}".getBytes()); os.write(jSONObject.toString().getBytes()); // Always get the Response code first . int responseCode = hc.getResponseCode(); if (responseCode == HttpConnection.HTTP_OK) { // You have successfully connected. int length = (int) hc.getLength(); System.out.println("length : " + length); byte[] data = null; if (length != -1) { data = new byte[length]; in = new DataInputStream(hc.openInputStream()); in.readFully(data); } else { // If content length is not given, read in chunks. int chunkSize = 512; int index = 0; int readLength = 0; in = new DataInputStream(hc.openInputStream()); 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; } return new String(data); // Image image = Image.createImage(data, 0, length); // ImageItem imageItem = new ImageItem(null, image, 0, null); // mForm.append(imageItem); // mForm.setTitle("Done."); } else { // Problem with your connection Dialog.show(null, "error downloading images", "OK", null); return null; } } catch (Exception e) { e.printStackTrace(); Dialog.show(null, "error downloading images", "OK", null); return null; } finally { if (in != null) { try { in.close(); } catch (IOException ex) { ex.printStackTrace(); } } if (os != null) { try { os.close(); } catch (IOException ex) { ex.printStackTrace(); } } if (hc != null) { try { hc.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
/** * Makes a http request to URL using the set method (HttpConnection.GET or HttpConnection.POST) * and the supplied request parameters. * * @param url * @param requestMethod * @param requestProperties User supplied Http request header parameters. * @param data if method is POST then the post data are in this array. * @param updateCurrentPage if set to true the HttpClient will remember the URL of this request in * order to handle feature relative path requests * @return * @throws InterruptedIOException * @throws SecurityException * @throws IOException * @throws IllegalStateException * @throws Exception */ public Response requestResource( String url, String requestMethod, Hashtable requestProperties, byte[] data, boolean updateCurrentPage) throws InterruptedIOException, SecurityException, IOException, IllegalStateException, Exception { url = getAbsolutEncodedURL(url); int idx = url.indexOf("://"); if (idx == -1) throw new IllegalArgumentException("URL must start with the protocol."); String protocol = url.substring(0, idx); if (protocol.equals("file")) { // Log.logInfo("File: ["+url+"]"); InputStream in = null; try { in = connector.openInputStream(url); } catch (Exception e) { Log.logDebug("Exception:" + e.getClass() + ": " + e.getMessage()); } if (in == null) { Log.logWarn("Failed to load local resource " + url); return null; } Response result = new Response("", "file", url.substring(7), in); if (updateCurrentPage) currentResponse = result; return result; } if (protocol.equals("rms")) { // Log.logInfo("File: ["+url+"]"); InputStream in = null; String rms = url.substring(6); try { in = connector.rmsRead(rms); } catch (Exception e) { Log.logDebug("Exception:" + e.getClass() + ": " + e.getMessage()); } if (in == null) { Log.logWarn("Failed to load local resource " + url); return null; } Response result = new Response("", "rms", rms, in); if (updateCurrentPage) currentResponse = result; return result; } HttpConnection conn = null; Log.logInfo(requestMethod + " [" + url + "]"); try { // the resource is located remotelly. Try to retrieve it. int mode = Connector.READ_WRITE; // XXX CREATING A READ ONLY CONNECTION WILL CAUSE SOME BLACKBERRY DEVICES NOT TO WORK. XXX // if(HttpConnection.POST.equals(requestMethod) && data!=null) mode=Connector.READ_WRITE; int code; Response result = new Response(); registerConnection(result); conn = (HttpConnection) connector.open(url, mode, true); conn.setRequestMethod(requestMethod); for (int i = 0; i < defaultHeaderValues.length; ++i) { conn.setRequestProperty(defaultHeaderValues[i][0], defaultHeaderValues[i][1]); } if (requestProperties != null) { Enumeration propKeys = requestProperties.keys(); while (propKeys.hasMoreElements()) { String key = (String) propKeys.nextElement(); String val = (String) requestProperties.get(key); conn.setRequestProperty(key, val); } } // add cookies String cookies = getCookies(conn, conn.getFile()); if (cookies.length() > 0) { conn.setRequestProperty("Cookie", cookies); } // add referer if (currentResponse != null && currentResponse.getProtocol().equals("file") == false) { String q = currentResponse.getQuery(); if (q != null) q = "?" + q; else q = ""; String referer = currentResponse.getBaseURL() + currentResponse.getFile() + q; conn.setRequestProperty("Referer", referer); } if (mode == Connector.READ_WRITE && data != null) // exoume na grapsoume kiolas. { conn.setRequestProperty("Content-Length", "" + data.length); OutputStream out = conn.openOutputStream(); out.write(data); out.close(); Log.logDebug("Post data[" + data.length + "] sent."); } Log.logDebug("Attempting to retrieve response code.."); code = conn.getResponseCode(); result.setConnection(conn); Log.logInfo("Response " + code + " " + conn.getResponseMessage()); for (int i = 0; i < 100; ++i) { String key = conn.getHeaderFieldKey(i); if (key == null) break; if (key.toLowerCase().equals("set-cookie")) { // the cookieStr may be more than one cookies separated by commas. // First we split the cookies and then we parse them. // this is a bit tricky since a cookie may contain commas as well...(who thought of that // delimiter anyway?) Vector cookieStrings = Cookie.splitCookies(conn.getHeaderField(i)); for (int j = 0; j < cookieStrings.size(); ++j) saveCookie((String) cookieStrings.elementAt(j), conn.getHost()); } else Log.logDebug(key + ": " + conn.getHeaderField(i)); } if (code == HttpConnection.HTTP_MOVED_PERM || code == HttpConnection.HTTP_MOVED_TEMP || // 301 or 307 redirect using the same method (post of get) code == HttpConnection.HTTP_SEE_OTHER) // must redirect using the GET method (see protocol) { if (updateCurrentPage) currentResponse = result; if (result.isCanceled()) throw new InterruptedIOException("Redirect canceled by user."); redirectCount++; String redirect = conn.getHeaderField("location"); Log.logInfo("Redirect[" + redirectCount + "] " + code + " to location: " + redirect); if (redirectCount < MAX_REDIRECTS) { try { conn.close(); } catch (IOException e) { Log.logWarn("HttpClient: Failed to close connection on redirect.", e); } conn = null; // make old connection null so on finally we will not try to unregister it // again. if (code == HttpConnection.HTTP_MOVED_PERM || code == HttpConnection.HTTP_MOVED_TEMP) return requestResource( redirect, requestMethod, requestProperties, data, updateCurrentPage); else return requestResource( redirect, HttpConnection.GET, requestProperties, data, updateCurrentPage); } else { throw new IllegalStateException("Too many redirects."); } } else // response is 200 or another http code. { if (updateCurrentPage && code == HttpConnection.HTTP_OK) // updateCurrentPage only when response is 200 (OK) currentResponse = result; return result; } } catch (Exception ex) { if (ex instanceof InterruptedIOException) Log.logInfo("USER Closed connection to " + url); else Log.logError("Request to " + url + " failed.", ex); if (conn != null) { try { conn.close(); } catch (IOException e) { Log.logWarn("Failed to close the connection.", e); } } throw ex; } finally { redirectCount = 0; } }
public static void Get(final String str, final Displayable retd) { final FIND[] tag = new FIND[7]; tag[0] = new FIND("returnfalse;\">"); tag[1] = new FIND("</a"); tag[2] = new FIND("setPosition("); tag[3] = new FIND(",null"); tag[4] = new FIND("search_more"); tag[5] = new FIND("search_results_entry\">"); tag[6] = new FIND("<a"); Location l = new Location(NAVI.getGP()); // //http://www.openstreetmap.org/geocoder/search_osm_nominatim?maxlat=44.48511276126&maxlon=34.135098728715&minlat=44.48511276126&minlon=34.135098728715&query=Lenina%2C+krivoy+rog String url = "http://www.openstreetmap.org/geocoder/search_osm_nominatim?maxlat=" + l.getLat() + "&maxlon=" + l.getLon() + "&minlat=" + l.getLat() + "&minlon=" + l.getLon() + "&query=" + TEXT.urlEncode(str); System.out.println(url); InputStream is = null; HttpConnection c = null; boolean read = false; st = new Stack(); String addressApendix = ""; System.out.println("openstreeet find"); try { try { final int BUFS = 1000; byte[] buf = new byte[BUFS]; c = (HttpConnection) Connector.open(url); // c.setRequestProperty( "User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; // rv:1.9.2.12) Gecko/20101026 MRA 5.7 (build 03686) Firefox/3.6.12 sputnik 2.3.0.76"); // c.setRequestProperty( "User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; // .NET CLR 1.0.3705;)" ); c.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0"); c.setRequestProperty("Accept-Language", Settings.accept_language); is = c.openInputStream(); int bufI = 0, ch; char bt; do { // if (MyCanvas.LOADING_CANCELED()){ // st.removeAllElements(); // return ; // } ch = is.read(); if (ch != 0xa && ch != 0x20) { bt = (char) ch; if (tag[5].find(bt)) { read = true; bufI = 0; } else if (read && tag[6].find(bt)) { addressApendix = new String(buf, 1, bufI - 2, "UTF-8"); addressApendix = TEXT.replace(addressApendix, "'", "'"); read = false; // System.out.println("@@@@@Address@@@@="+address); } else if (tag[0].find(bt)) { read = true; bufI = 0; } else if (read && tag[1].find(bt)) { String address = new String(buf, 1, bufI - 3, "UTF-8"); address = TEXT.replace(address, "'", "'"); // System.out.println(new String(buf)); st.addElement(addressApendix + " " + address); read = false; // System.out.println("@@@@@Address@@@@="+address); } else if (tag[2].find(bt)) { read = true; bufI = 0; } else if (read && tag[3].find(bt)) { String coordinates = new String(buf, 1, bufI - 5, "UTF-8"); String[] locs = TEXT.split(coordinates, ','); l = new Location(Double.parseDouble(locs[0]), Double.parseDouble(locs[1])); st.addElement(l); read = true; bufI = 0; // System.out.println("@@@@Coordinates@@@@="+coordinates); } else if (tag[4].find(bt)) { System.out.println("SEARCH MORE"); break; } // if (read==true && bufI<BUFS) // buf[bufI++]=(byte)bt; } if (read == true && bufI < BUFS) buf[bufI++] = (byte) ch; } while (ch != -1); } finally { if (is != null) is.close(); if (is != null) c.close(); } } catch (Exception ex) { System.out.println(ex.toString()); } // MyCanvas.SetErrorText(ex.toString());} List(str, retd); }
/** {@inheritDoc} */ public InputStream resourceRequested(DocumentInfo docInfo) { InputStream is = null; String url = docInfo.getUrl(); String linkDomain = getDomainForLinks(url); // Visited links if (docInfo.getExpectedContentType() == DocumentInfo.TYPE_HTML) { // Only mark base documents as visited links if (linkDomain != null) { Vector hostVisitedLinks = (Vector) visitedLinks.get(linkDomain); if (hostVisitedLinks == null) { hostVisitedLinks = new Vector(); visitedLinks.put(linkDomain, hostVisitedLinks); } if (!hostVisitedLinks.contains(url)) { hostVisitedLinks.addElement(url); Storage.addHistory(linkDomain, url); } } else { System.out.println("Link domain null for " + url); } } String params = docInfo.getParams(); if ((!docInfo.isPostRequest()) && (params != null) && (!params.equals(""))) { url = url + "?" + params; } // See if page/image is in the cache // caching will be used only if there are no parameters and no cookies (Since if they are this // is probably dynamic content) boolean useCache = false; if (((docInfo.getExpectedContentType() == DocumentInfo.TYPE_HTML) && (CACHE_HTML) && ((params == null) || (params.equals(""))) && (!cookiesExistForDomain(linkDomain))) || ((docInfo.getExpectedContentType() == DocumentInfo.TYPE_IMAGE) && (CACHE_IMAGES))) { useCache = true; InputStream imageIS = Storage.getResourcefromCache(url); if (imageIS != null) { return imageIS; } } // Handle the file protocol if (url.startsWith("file://")) { return getFileStream(docInfo); } try { HttpConnection hc = (HttpConnection) Connector.open(url); String encoding = null; if (docInfo.isPostRequest()) { encoding = "application/x-www-form-urlencoded"; } if (!docInfo.getEncoding().equals(DocumentInfo.ENCODING_ISO)) { encoding = docInfo.getEncoding(); } // hc.setRequestProperty("Accept_Language","en-US"); // String domain=hc.getHost(); // sub.domain.com / sub.domain.co.il String domain = linkDomain; // will return one of the following formats: sub.domain.com / sub.domain.co.il sendCookies(domain, hc); domain = domain.substring(domain.indexOf('.')); // .domain.com / .domain.co.il if (domain.indexOf('.', 1) != -1) { // Make sure that we didn't get just .com - TODO - however note that if the // domain was domain.co.il - it can be here .co.il sendCookies(domain, hc); } if (encoding != null) { hc.setRequestProperty("Content-Type", encoding); } if (docInfo.isPostRequest()) { hc.setRequestMethod(HttpConnection.POST); byte[] paramBuf = params.getBytes(); hc.setRequestProperty("Content-Length", "" + paramBuf.length); OutputStream os = hc.openOutputStream(); os.write(paramBuf); os.close(); // os.flush(); // flush is said to be problematic in some devices, uncomment if it is // necessary for your device } if (docInfo.getExpectedContentType() == DocumentInfo .TYPE_HTML) { // We perform these checks only for text (i.e. main page), for images we // just send what the server sends and "hope for the best" String contentTypeStr = hc.getHeaderField("content-type").toLowerCase(); if (contentTypeStr != null) { if ((contentTypeStr.startsWith("text/")) || (contentTypeStr.startsWith("application/xhtml")) || (contentTypeStr.startsWith("application/vnd.wap"))) { docInfo.setExpectedContentType(DocumentInfo.TYPE_HTML); } else if (contentTypeStr.startsWith("image/")) { docInfo.setExpectedContentType(DocumentInfo.TYPE_IMAGE); hc.close(); return getStream("<img src=\"" + url + "\">", null); } else { hc.close(); return getStream("Content type " + contentTypeStr + " is not supported.", "Error"); } } int charsetIndex = contentTypeStr.indexOf("charset="); String charset = contentTypeStr.substring(charsetIndex + 8); if ((charset.startsWith("utf-8")) || (charset.startsWith("utf8"))) { // startwith to allow trailing white spaces docInfo.setEncoding(DocumentInfo.ENCODING_UTF8); } } int i = 0; while (hc.getHeaderFieldKey(i) != null) { if (hc.getHeaderFieldKey(i).equals("set-cookie")) { // addCookie(hc.getHeaderField(i), hc); addCookie(hc.getHeaderField(i), url); } i++; } int response = hc.getResponseCode(); if (response / 100 == 3) { // 30x code is redirect String newURL = hc.getHeaderField("Location"); if (newURL != null) { hc.close(); docInfo.setUrl(newURL); // docInfo.setPostRequest(false); // docInfo.setParams(null); //reset params return resourceRequested(docInfo); } } is = hc.openInputStream(); if (useCache) { byte[] buf = getBuffer(is); Storage.addResourceToCache(url, buf, false); ByteArrayInputStream bais = new ByteArrayInputStream(buf); is.close(); hc.close(); // all the data is in the buffer return bais; } } catch (IOException e) { System.out.println("HttpRequestHandler->IOException: " + e.getMessage()); } catch (IllegalArgumentException e) { // For malformed URL System.out.println("HttpRequestHandler->IllegalArgumentException: " + e.getMessage()); } return is; }
public InputStream makeRequest(String url, OutputStream pos) throws IOException { HttpConnection conn = null; ByteArrayOutputStream bos = null; DataInputStream is = null; DataOutputStream os = null; InputStream pis = null; try { conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE); conn.setRequestMethod(HttpConnection.POST); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestProperty("Accept", "application/octet-stream"); if (sessionCookie == null) { conn.setRequestProperty("version", "???"); } else { conn.setRequestProperty("cookie", sessionCookie); } // Getting the output stream may flush the headers os = conn.openDataOutputStream(); os.write(pos.getBytes()); os.close(); int responseCode; try { responseCode = conn.getResponseCode(); } catch (IOException e) { throw new IOException("No response from " + url); } if (responseCode != HttpConnection.HTTP_OK) { throw new IllegalArgumentException(); } bos = new ByteArrayOutputStream(); { is = conn.openDataInputStream(); String sc = conn.getHeaderField("set-cookie"); if (sc != null) { sessionCookie = sc; } while (true) { int ch = is.read(); if (ch == -1) break; bos.write(ch); } is.close(); is = null; conn.close(); conn = null; } pis = new InputStream(bos.toByteArray()); bos.close(); bos = null; } catch (Exception e) { e.printStackTrace(); try { if (conn != null) { conn.close(); conn = null; } if (bos != null) { bos.close(); bos = null; } if (is != null) { is.close(); is = null; } } catch (Exception exc) { } throw new IOException(); } return pis; }