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(); } }
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); } }
/** * 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; } }