List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:ict.servlet.UploadToServer.java
public static int upLoad2Server(String sourceFileUri) { String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp"; // String [] string = sourceFileUri; String fileName = sourceFileUri; int serverResponseCode = 0; HttpURLConnection conn = null; DataOutputStream dos = null;//from w ww .j a v a2 s .c o m DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String responseFromServer = ""; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { return 0; } try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); // create a buffer of maximum size bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); // close streams m_log.info("Upload file to server" + fileName + " File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { // ex.printStackTrace(); m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex); } catch (Exception e) { // e.printStackTrace(); } //this block will give the response of upload link /* try { BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { m_log.info("Huzza" + "RES Message: " + line); } rd.close(); } catch (IOException ioex) { m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex); }*/ return serverResponseCode; // like 200 (Ok) }
From source file:com.baseproject.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());//from ww w .j a va2 s .c om map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException(Util.buildHttpErrorMsg("failed", -1, "URL blocked by rewriter: " + url)); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); // if (responseCode == -1) { // // -1 is returned by getResponseCode() if the response code could not be retrieved. // // Signal to the caller that something was wrong with the connection. // throw new IOException("Could not retrieve response code from HttpUrlConnection."); // } if (responseCode != HttpStatus.SC_NOT_MODIFIED && responseCode != HttpURLConnection.HTTP_OK) { InputStream in = null; try { in = connection.getErrorStream(); } catch (Exception e) { e.printStackTrace(); } if (in == null) { throw new IOException(Util.buildHttpErrorMsg("failed", responseCode, "unknown")); } else { throw new IOException(Util.convertStreamToString(in)); } } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { if (header.getKey().equals("Set-Cookie")) { List<String> cookieValue = header.getValue(); for (String c : cookieValue) { Header h = new BasicHeader(header.getKey(), c); response.addHeader(h); } } else { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } } return response; }
From source file:com.android.volley.toolbox.AuthenticationChallengesProofHurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*w w w . ja v a 2 s . c om*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); /************************/ /****** WORKAROUND ******/ int responseCode; try { // Will throw IOException if server responds with 401. responseCode = connection.getResponseCode(); } catch (IOException e) { // You can get the response code after an exception if you call .getResponseCode() // a second time on the connection object. This is because the first time you // call .getResponseCode() an internal state is set that enables .getResponseCode() // to return without throwing an exception. responseCode = connection.getResponseCode(); } /************************/ if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:hudson.remoting.Engine.java
@SuppressWarnings({ "ThrowableInstanceNeverThrown" }) @Override/*from w w w. j av a 2 s.co m*/ public void run() { try { boolean first = true; while (true) { if (first) { first = false; } else { if (noReconnect) return; // exit } listener.status("Locating server among " + candidateUrls); Throwable firstError = null; String port = null; for (URL url : candidateUrls) { String s = url.toExternalForm(); if (!s.endsWith("/")) s += '/'; URL salURL = new URL(s + "tcpSlaveAgentListener/"); // find out the TCP port HttpURLConnection con = (HttpURLConnection) salURL.openConnection(); if (con instanceof HttpURLConnection && credentials != null) { String encoding = new String(Base64.encodeBase64(credentials.getBytes())); con.setRequestProperty("Authorization", "Basic " + encoding); } try { try { con.setConnectTimeout(30000); con.setReadTimeout(60000); con.connect(); } catch (IOException x) { if (firstError == null) { firstError = new IOException( "Failed to connect to " + salURL + ": " + x.getMessage()).initCause(x); } continue; } port = con.getHeaderField("X-Hudson-JNLP-Port"); if (con.getResponseCode() != 200) { if (firstError == null) firstError = new Exception(salURL + " is invalid: " + con.getResponseCode() + " " + con.getResponseMessage()); continue; } if (port == null) { if (firstError == null) firstError = new Exception(url + " is not Hudson"); continue; } } finally { con.disconnect(); } // this URL works. From now on, only try this URL hudsonUrl = url; firstError = null; candidateUrls = Collections.singletonList(hudsonUrl); break; } if (firstError != null) { listener.error(firstError); return; } Socket s = connect(port); listener.status("Handshaking"); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); BufferedInputStream in = new BufferedInputStream(s.getInputStream()); dos.writeUTF("Protocol:JNLP2-connect"); Properties props = new Properties(); props.put("Secret-Key", secretKey); props.put("Node-Name", slaveName); if (cookie != null) props.put("Cookie", cookie); ByteArrayOutputStream o = new ByteArrayOutputStream(); props.store(o, null); dos.writeUTF(o.toString("UTF-8")); String greeting = readLine(in); if (greeting.startsWith("Unknown protocol")) { LOGGER.info("The server didn't understand the v2 handshake. Falling back to v1 handshake"); s.close(); s = connect(port); in = new BufferedInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:JNLP-connect"); dos.writeUTF(secretKey); dos.writeUTF(slaveName); greeting = readLine(in); // why, oh why didn't I use DataOutputStream when writing to the network? if (!greeting.equals(GREETING_SUCCESS)) { onConnectionRejected(greeting); continue; } } else { if (greeting.equals(GREETING_SUCCESS)) { Properties responses = readResponseHeaders(in); cookie = responses.getProperty("Cookie"); } else { onConnectionRejected(greeting); continue; } } final Socket socket = s; final Channel channel = new Channel("channel", executor, in, new BufferedOutputStream(s.getOutputStream())); PingThread t = new PingThread(channel) { protected void onDead() { try { if (!channel.isInClosed()) { LOGGER.info("Ping failed. Terminating the socket."); socket.close(); } } catch (IOException e) { LOGGER.log(SEVERE, "Failed to terminate the socket", e); } } }; t.start(); listener.status("Connected"); channel.join(); listener.status("Terminated"); t.interrupt(); // make sure the ping thread is terminated listener.onDisconnect(); if (noReconnect) return; // exit // try to connect back to the server every 10 secs. waitForServerToBack(); } } catch (Throwable e) { listener.error(e); } }
From source file:com.PAB.ibeaconreference.AppEngineSpatial.java
public static Response getOrPost(Request request) { mErrorMessage = null;//www.j av a 2 s .c om HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof PUT) { byte[] payload = ((PUT) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); if (a == 401) { response = new Response(a, conn.getHeaderFields(), new byte[] {}); } InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); a12 = new String(body, "US-ASCII"); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * CRL- ? , ? ? , ? ?/*from w w w .j ava 2 s . c o m*/ * ? * * @param crlName */ private void loadCrlObject(String crlName) { TypeOfCrlLoaded oldState = MAP_OF_LOAD_CRL_LABEL.get(crlName); if (TypeOfCrlLoaded.LOADING.equals(oldState)) { return; } MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADING); String location = MAP_OF_CRL_PATH.get(crlName); try { URL url = new URL(location); HttpURLConnection conn = null; if (useProxy) { Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); } else { conn = (HttpURLConnection) url.openConnection(); } conn.setUseCaches(false); conn.setDoInput(true); conn.connect(); if (conn.getResponseCode() == 200) { CertificateFactory cf = CertificateFactory.getInstance("X.509", "KALKAN"); X509CRL crlObject = (X509CRL) cf.generateCRL(conn.getInputStream()); MAP_OF_XCRL.put(crlName, crlObject); } else { String msg = "(1) ? CRL- : '" + location + "' : " + conn.getResponseCode() + " , " + conn.getResponseMessage(); log.warning(msg); } } catch (Exception e) { String msg = "(1) ? CRL- : '" + location + "' : " + e.getMessage(); log.warning(msg); } //MAP_OF_LOAD_CRL_LABEL.put(crlName, oldState ) ; MAP_OF_LOAD_CRL_TIME.put(crlName, new Date()); MAP_OF_LOAD_CRL_LABEL.put(crlName, TypeOfCrlLoaded.LOADED); }
From source file:export.NikePlus.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;/*from w ww. jav a2 s . c o m*/ if ((s = connect()) != Status.OK) { return s; } NikeXML nikeXML = new NikeXML(db); GPX nikeGPX = new GPX(db); HttpURLConnection conn = null; Exception ex = null; try { StringWriter xml = new StringWriter(); nikeXML.export(mID, xml); StringWriter gpx = new StringWriter(); nikeGPX.export(mID, gpx); String url = String.format(SYNC_URL, access_token); conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("user-agent", USER_AGENT); conn.addRequestProperty("appid", APP_ID); Part<StringWritable> part1 = new Part<StringWritable>("runXML", new StringWritable(xml.toString())); part1.filename = "runXML.xml"; part1.contentType = "text/plain; charset=US-ASCII"; part1.contentTransferEncoding = "8bit"; Part<StringWritable> part2 = new Part<StringWritable>("gpxXML", new StringWritable(gpx.toString())); part2.filename = "gpxXML.xml"; part2.contentType = "text/plain; charset=US-ASCII"; part2.contentTransferEncoding = "8bit"; Part<?> parts[] = { part1, part2 }; postMulti(conn, parts); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); conn.connect(); if (responseCode != 200) { throw new Exception(amsg); } url = String.format(SYNC_COMPLETE_URL, access_token); conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("user-agent", USER_AGENT); conn.addRequestProperty("appid", APP_ID); responseCode = conn.getResponseCode(); amsg = conn.getResponseMessage(); conn.disconnect(); if (responseCode == 200) { return Status.OK; } ex = new Exception(amsg); } catch (Exception e) { ex = e; } s = Uploader.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:com.centurylink.mdw.ant.taskdef.HttpTransfer.java
public void uploadFile(URL destURL, File file, String userId, String password, boolean overwrite) { try {/*from w w w . j a va2 s . c o m*/ log("target url... " + destURL.toString()); long fileLastModified = file.lastModified(); HttpURLConnection conn = (HttpURLConnection) destURL.openConnection(); long urlLastModified = conn.getLastModified(); conn.disconnect(); if (!overwrite && (urlLastModified >= fileLastModified)) { log("Destination file is up-to-date, not uploading."); return; } else { conn = (HttpURLConnection) destURL.openConnection(); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.setRequestMethod("PUT"); if (userId != null) { String value = userId + ":" + password; conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(value.getBytes()))); } conn.setDoOutput(true); OutputStream outStream = conn.getOutputStream(); log("Uploading... " + file); InputStream inStream = new FileInputStream(file); byte[] buf = new byte[1024]; int len = 0; while (len != -1) { len = inStream.read(buf); if (len > 0) outStream.write(buf, 0, len); } inStream.close(); outStream.close(); conn.disconnect(); int code = conn.getResponseCode(); if (code < 200 || code >= 300) { String response = conn.getResponseMessage(); throw new BuildException("Error uploading file: " + code + " -- " + response); } log(" Uploaded: " + destURL); } } catch (IOException e) { if (isFailOnError()) throw new BuildException(e.getMessage(), e); else log(e.getMessage()); } }
From source file:edu.pdx.cecs.orcycle.UserFeedbackUploader.java
boolean uploadUserInfoV4() { boolean result = false; final String postUrl = mCtx.getResources().getString(R.string.post_url); try {/*from w ww .j av a 2 s . c o m*/ URL url = new URL(postUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); conn.setRequestProperty("Cycleatl-Protocol-Version", "4"); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); JSONObject jsonUser; if (null != (jsonUser = getUserJSON())) { try { String deviceId = userId; dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n"); dos.writeBytes( fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n"); dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n"); dos.writeBytes(fieldSep); dos.flush(); } catch (Exception ex) { Log.e(MODULE_TAG, ex.getMessage()); return false; } finally { dos.close(); } int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); // JSONObject responseData = new JSONObject(serverResponseMessage); Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 201 || serverResponseCode == 202) { // TODO: Record somehow that data was uploaded successfully result = true; } } else { result = false; } } catch (IllegalStateException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); return false; } return result; }