/** * Get the OutputStream from the platform-specific HTTP connection * * @return * @throws IOException */ public OutputStream getOutputStream() throws IOException { if (os == null) { os = httpConnection.openOutputStream(); } return os; }
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(); } }
/** * 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); }
/** * 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(); }
/** {@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); } }
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 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; }
/** * 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; } }