/** * Create a platform-specific HTTP network connection, and set the HTTP header with the * corresponding key-value pairs * * @param url * @param requestPropertyKeys - a list of header keys * @param requestPropertyValues - a list of associated header values * @throws IOException */ public JMEHttpConn( final String url, final Vector requestPropertyKeys, final Vector requestPropertyValues) throws IOException { httpConnection = (HttpConnection) Connector.open(url); for (int i = 0; i < requestPropertyKeys.size(); i++) { httpConnection.setRequestProperty( (String) requestPropertyKeys.elementAt(i), (String) requestPropertyValues.elementAt(i)); } }
private GcfHttpRepresentation(String url, RequestInfo requestInfo, String eTag) throws IOException { this.originalRequest = requestInfo; DateTime requestTime = DateTime.now(); connection = (HttpConnection) Connector.open(url); meta = new LiveGcfResponseInfo(connection, requestTime); connection.setRequestProperty(RequestHeaderName.IfNoneMatch.name(), eTag); is = connection.openInputStream(); }
/** * Services the request. * * @param host The {@link HttpHost} for the target server * @return An {@link HttpResponse} with the reply from the server * @throws IOException if something went wrong during the network communication */ final HttpResponse handleConnection(HttpHost host) throws IOException { // open the connection, this will resolve the URL as well String url = host.toURI() + m_requestURI; // get transport for http url += m_transportType.getHTTPConnectionParameters(); HttpConnection conn = (HttpConnection) Connector.open(url); // set method and headers conn.setRequestMethod(getRequestMethod()); Enumeration keysEnum = m_headers.keys(); while (keysEnum.hasMoreElements()) { String key = (String) keysEnum.nextElement(); String value = (String) m_headers.get(key); conn.setRequestProperty(key, value); } if (m_entity != null) { // if we have an entity attached, send that information // set the connection in output mode // send extra headers String encoding = m_entity.getContentEncoding(); if (encoding != null) { conn.setRequestProperty("Content-Encoding", encoding); } String type = m_entity.getContentType(); if (type != null) { conn.setRequestProperty("Content-Type", type); } OutputStream os = null; try { os = conn.openOutputStream(); m_entity.writeTo(os); } finally { os.close(); } } m_transportType.setHTTPHeaders(conn); conn.getResponseCode(); // trigger transaction return new BlackBerryHttpResponse(conn); }
private static void setRequestHeaders(HttpConnection connection, RequestInfo requestInfo) throws IOException { if (requestInfo == null) { return; } String requestHeader; for (int i = 0; (requestHeader = requestInfo.headerName(i)) != null; ++i) { connection.setRequestProperty(requestHeader, requestInfo.headerValue(i)); } }
/** * Sends the avaiable cookies for the given domain * * @param domain The cookies domain * @param hc Teh HTTPConnection * @throws IOException */ private void sendCookies(String domain, HttpConnection hc) throws IOException { // System.out.println("Sending cookies for "+domain); Hashtable hostCookies = (Hashtable) cookies.get(domain); if (hostCookies != null) { for (Enumeration e = hostCookies.keys(); e.hasMoreElements(); ) { String name = (String) e.nextElement(); String value = (String) hostCookies.get(name); String cookie = name + "=" + value; // System.out.println("Cookie sent: "+cookie); hc.setRequestProperty("cookie", cookie); } } }
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); }
/** * Method to configure the HTTP request stream. This method will do whatever mechanics are * necessary to utilize the HTTP connection object to return an output stream to be utilized to * send the HTTP request. * * @param http the HttpConnection object, unopened, with no headers or any configuration yet set * @return an OutputStream which can be used to write the request data to this HTTP request. */ protected OutputStream setupReqStream(HttpConnection http) throws IOException { http.setRequestMethod(HttpConnection.POST); http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0"); http.setRequestProperty("Content-Language", "en-US"); http.setRequestProperty("Content-Type", "text/xml"); String soapAction = getProperty(Operation.SOAPACTION_URI_PROPERTY); if (soapAction == null || "".equals(soapAction)) { soapAction = "\"\""; } else { if (!soapAction.startsWith("\"")) { soapAction = "\"" + soapAction; } if (!soapAction.endsWith("\"")) { soapAction = soapAction + "\""; } } http.setRequestProperty("SOAPAction", soapAction); String useSession = getProperty(Stub.SESSION_MAINTAIN_PROPERTY); if (useSession != null && useSession.toLowerCase().equals("true")) { String cookie = getSessionCookie(getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY)); if (cookie != null) { http.setRequestProperty("Cookie", cookie); } } String s1 = getProperty(Stub.USERNAME_PROPERTY); String s2 = getProperty(Stub.PASSWORD_PROPERTY); if (s1 != null && s2 != null) { byte[] encodeData = (s1 + ":" + s2).getBytes(); http.setRequestProperty( "Authorization", "Basic " + Base64.encode(encodeData, 0, encodeData.length)); } return http.openOutputStream(); }
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; }
/** {@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 void upload() throws IOException { logger.info(Locale.get("guigpxosmupload.UploadingOSMGPX") /*Uploading OSM GPX*/); int respCode; String respMessage; try { HttpConnection connection = (HttpConnection) Connector.open(url); System.out.println(Locale.get("guigpxosmupload.Connection") /*Connection: */ + connection); connection.setRequestMethod(HttpConnection.POST); connection.setRequestProperty("Connection", "close"); connection.setRequestProperty("User-Agent", "GpsMid"); connection.setRequestProperty( "Authorization", "Basic " + Base64.encode(Configuration.getOsmUsername() + ":" + Configuration.getOsmPwd())); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(baos); osw.write("-----------------------------12132519071893744613145780879\r\n"); osw.write("Content-Disposition: form-data; name=\"file\"; filename=\"" + name + "\"\r\n"); osw.write("Content-Type: application/octet-stream\r\n\r\n"); osw.write(new String(gpxOS.toByteArray())); osw.write("-----------------------------12132519071893744613145780879\r\n"); osw.write("Content-Disposition: form-data; name=\"tags\"\r\n\r\n"); osw.write(tags + "\r\n"); osw.write("-----------------------------12132519071893744613145780879\r\n"); osw.write("Content-Disposition: form-data; name=\"description\"\r\n\r\n"); osw.write(description + "\r\n"); osw.write("-----------------------------12132519071893744613145780879\r\n"); osw.write("Content-Disposition: form-data; name=\"public\"\r\n\r\n"); osw.write(publicFlag ? "1" : "0" + "\r\n"); osw.write("-----------------------------12132519071893744613145780879--\r\n"); osw.flush(); connection.setRequestProperty("Content-Length", Integer.toString(baos.toByteArray().length)); connection.setRequestProperty( "Content-Type", "multipart/form-data; boundary=---------------------------12132519071893744613145780879"); OutputStream os = connection.openOutputStream(); os.write(baos.toByteArray()); os.flush(); // HTTP Response respCode = connection.getResponseCode(); respMessage = connection.getResponseMessage(); } catch (Exception e) { e.printStackTrace(); throw new IOException( Locale.get("guigpxosmupload.FailedUploadingGPX") /*Failed uploading GPX: */ + e.getMessage()); } if (respCode == HttpConnection.HTTP_OK) { logger.info("Successfully uploaded GPX"); } else { throw new IOException( Locale.get("guigpxosmupload.GPXTraceNotAccepted") /*GPX trace was not accepted (*/ + respCode + "): " + respMessage); } }
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); }
public void run() { for (; ; ) { while (!_start && !_stop) { try { sleep(TIMEOUT); } catch (InterruptedException e) { System.err.println(e.toString()); } } if (_stop) { return; } synchronized (this) { String url = null; StreamConnection s = null; DataInputStream dis = null; java.io.InputStream input = null; try { s = (StreamConnection) Connector.open(getUrl(), Connector.READ, true); HttpConnection httpConn = (HttpConnection) s; httpConn.setRequestProperty("User-Agent", ipokiUserAgent); int status = httpConn.getResponseCode(); if (status == HttpConnection.HTTP_OK) { try { DocumentBuilder doc = DocumentBuilderFactory.newInstance().newDocumentBuilder(); dis = s.openDataInputStream(); Document d = doc.parse(dis); dis.close(); dis = null; Element el = d.getDocumentElement(); _theUrl = el.getFirstChild().getNodeValue(); url = getUrl(); } catch (SAXException e) { System.err.println(e.toString()); } catch (ParserConfigurationException e) { System.err.println(e.toString()); } } s.close(); s = null; if (url != null) { s = (StreamConnection) Connector.open(url); httpConn = (HttpConnection) s; httpConn.setRequestProperty("User-Agent", ipokiUserAgent); status = httpConn.getResponseCode(); if (status == HttpConnection.HTTP_OK) { bv.addElement(data[0]); input = s.openInputStream(); byte[] data = new byte[1]; ByteVector bv = new ByteVector(); while (-1 != input.read(data)) { bv.addElement(data[0]); } final byte[] png = bv.getArray(); input.close(); input = null; s.close(); s = null; try { _mapScreen._app.invokeLater( new Runnable() { public void run() { _mapScreen.mapField.setBitmap(Bitmap.createBitmapFromPNG(png, 0, -1)); } }); } catch (Exception e) { System.err.println(e.toString()); } } } } catch (java.io.IOException e) { System.err.println(e.toString()); } finally { try { if (dis != null) { dis.close(); dis = null; } } catch (java.io.IOException e) { // pass } try { if (input != null) { input.close(); input = null; } } catch (java.io.IOException e) { // pass } try { if (s != null) { s.close(); s = null; } } catch (java.io.IOException e) { // pass } } _start = false; } // synchronized } // for } // run
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 } }
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 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; }
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); }