List of usage examples for java.net HttpURLConnection getResponseMessage
public String getResponseMessage() throws IOException
From source file:de.fu_berlin.inf.dpp.netbeans.feedback.FileSubmitter.java
/** * Tries to upload the given file to the given HTTP server (via POST * method)./* w w w . j a v a 2 s . co m*/ * * @param file * the file to upload * @param url * the URL of the server, that is supposed to handle the file * @param monitor * a monitor to report progress to * @throws IOException * if an I/O error occurs * */ public static void uploadFile(final File file, final String url, IProgressMonitor monitor) throws IOException { final String CRLF = "\r\n"; final String doubleDash = "--"; final String boundary = generateBoundary(); HttpURLConnection connection = null; OutputStream urlConnectionOut = null; FileInputStream fileIn = null; if (monitor == null) monitor = new NullProgressMonitor(); int contentLength = (int) file.length(); if (contentLength == 0) { log.warn("file size of file " + file.getAbsolutePath() + " is 0 or the file does not exist"); return; } monitor.beginTask("Uploading file " + file.getName(), contentLength); try { URL connectionURL = new URL(url); if (!"http".equals(connectionURL.getProtocol())) throw new IOException("only HTTP protocol is supported"); connection = (HttpURLConnection) connectionURL.openConnection(); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setReadTimeout(TIMEOUT); connection.setConnectTimeout(TIMEOUT); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); String contentDispositionLine = "Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"" + CRLF; String contentTypeLine = "Content-Type: application/octet-stream; charset=ISO-8859-1" + CRLF; String contentTransferEncoding = "Content-Transfer-Encoding: binary" + CRLF; contentLength += 2 * boundary.length() + contentDispositionLine.length() + contentTypeLine.length() + contentTransferEncoding.length() + 4 * CRLF.length() + 3 * doubleDash.length(); connection.setFixedLengthStreamingMode(contentLength); connection.connect(); urlConnectionOut = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConnectionOut, "US-ASCII"), true); writer.append(doubleDash).append(boundary).append(CRLF); writer.append(contentDispositionLine); writer.append(contentTypeLine); writer.append(contentTransferEncoding); writer.append(CRLF); writer.flush(); fileIn = new FileInputStream(file); byte[] buffer = new byte[8192]; for (int read = 0; (read = fileIn.read(buffer)) > 0;) { if (monitor.isCanceled()) return; urlConnectionOut.write(buffer, 0, read); monitor.worked(read); } urlConnectionOut.flush(); writer.append(CRLF); writer.append(doubleDash).append(boundary).append(doubleDash).append(CRLF); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { log.debug("uploaded file " + file.getAbsolutePath() + " to " + connectionURL.getHost()); return; } throw new IOException("failed to upload file " + file.getAbsolutePath() + connectionURL.getHost() + " [" + connection.getResponseMessage() + "]"); } finally { IOUtils.closeQuietly(fileIn); IOUtils.closeQuietly(urlConnectionOut); if (connection != null) connection.disconnect(); monitor.done(); } }
From source file:my.swingconnect.SwingConnectUI.java
public int uploadFile(String User, String Pass) { int set = 0;//from w ww .j a v a 2 s. com String upLoadServerUri = null; upLoadServerUri = "http://photo-drop.com/clientlogin.php"; final String USER_AGENT = "Mozilla/5.0"; HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; if (User.isEmpty() && Pass.isEmpty()) { System.out.println("Please enter the valid User and Pass :"); return set; } else { try { //String upLoadServerUri = null; int serverResponseCode = 0; URL url = new URL(upLoadServerUri); //Passing the server complete URL // Open a HTTP connection to the URL 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("User-Agent", USER_AGENT); conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //conn.setRequestProperty("Cookie", "Username=Mavericks;"); String urlParameters = "Username=" + User + "&Password=" + Pass + "&submit=Login"; dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(urlParameters); dos.flush(); dos.close(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); System.out.println("HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { System.out.println("Posted success"); set = 1; } else if (serverResponseCode == 401) { System.out.println("Invalid Login"); } else { System.out.println("Error check"); } } catch (MalformedURLException ex) { ex.printStackTrace(); System.out.println("Error"); } catch (Exception e) { e.printStackTrace(); System.out.println("Error"); } return set; } }
From source file:dk.clarin.tools.workflow.java
/** * Sends an HTTP GET request to a url//from ww w . ja v a2s . c o m * * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search") * @param requestString - all the request parameters (Example: "param1=val1¶m2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself * @return - The response from the end point */ public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat, String filename, String jobID, boolean postmethod) { int code = 0; String message = ""; //String filelist; if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) { // Send a GET or POST request to the servlet try { // Construct data String requestResult = ""; String urlStr = endpoint; if (postmethod) // HTTP POST { logger.debug("HTTP POST"); StringReader input = new StringReader(requestString); StringWriter output = new StringWriter(); URL endp = new URL(endpoint); HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endp.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(input, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) out.close(); } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endp + " ?): " + e); } finally { if (urlc != null) { code = urlc.getResponseCode(); if (code == 200) { got200(result, BracMat, filename, jobID, urlc.getInputStream()); } else { InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); requestResult = output.toString(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) in.close(); } logger.debug("urlc.getResponseCode() == {}", code); message = urlc.getResponseMessage(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } urlc.disconnect(); } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } //requestResult = output.toString(); logger.debug("postData returns " + requestResult); } else // HTTP GET { logger.debug("HTTP GET"); // Send data if (requestString != null && requestString.length() > 0) { urlStr += "?" + requestString; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.connect(); // Cast to a HttpURLConnection if (conn instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) conn; code = httpConnection.getResponseCode(); logger.debug("httpConnection.getResponseCode() == {}", code); message = httpConnection.getResponseMessage(); BufferedReader rd; StringBuilder sb = new StringBuilder(); ; //String line; if (code == 200) { got200(result, BracMat, filename, jobID, httpConnection.getInputStream()); } else { // Get the error response rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream())); int nextChar; while ((nextChar = rd.read()) != -1) { sb.append((char) nextChar); } rd.close(); requestResult = sb.toString(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } logger.debug("Job " + jobID + " receives status code [" + code + "] from tool."); } catch (Exception e) { //jobs = 0; // No more jobs to process now, probably the tool is not reachable logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage()); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } } else { //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint + ")"); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } return code; }
From source file:com.juick.android.Utils.java
public static RESTResponse postJSON(final Context context, final String url, final String data, final String contentType) { final URLAuth authorizer = getAuthorizer(url); final RESTResponse[] ret = new RESTResponse[] { null }; final boolean[] cookieCleared = new boolean[] { false }; authorizer.authorize(context, false, false, url, new Function<Void, String>() { @Override/*from w w w . j a v a2s .c o m*/ public Void apply(String myCookie) { final boolean noAuthRequested = myCookie != null && myCookie.equals(URLAuth.REFUSED_AUTH); if (noAuthRequested) myCookie = null; HttpURLConnection conn = null; try { String nurl = authorizer.authorizeURL(url, myCookie); URL jsonURL = new URL(nurl); conn = (HttpURLConnection) jsonURL.openConnection(); if (contentType != null) { conn.addRequestProperty("Content-Type", contentType); } authorizer.authorizeRequest(context, conn, myCookie, nurl); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.close(); URLAuth.ReplyCode authReplyCode = authorizer.validateNon200Reply(conn, url, false); try { if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && noAuthRequested) { ret[0] = new RESTResponse(NO_AUTH, false, null); } else if (authReplyCode == URLAuth.ReplyCode.FORBIDDEN && !cookieCleared[0]) { cookieCleared[0] = true; // don't enter loop final Function<Void, String> thiz = this; authorizer.clearCookie(context, new Runnable() { @Override public void run() { authorizer.authorize(context, true, false, url, thiz); } }); } else { if (conn.getResponseCode() == 200 || authReplyCode == URLAuth.ReplyCode.NORMAL) { InputStream inputStream = conn.getInputStream(); ret[0] = streamToString(inputStream, null); inputStream.close(); } else { ret[0] = new RESTResponse( "HTTP " + conn.getResponseCode() + " " + conn.getResponseMessage(), false, null); } } } finally { conn.disconnect(); } } catch (Exception e) { Log.e("getJSON", e.toString()); ret[0] = new RESTResponse(ServerToClient.NETWORK_CONNECT_ERROR + e.toString(), true, null); } finally { if (conn != null) { conn.disconnect(); } } return null; //To change body of implemented methods use File | Settings | File Templates. } }); while (ret[0] == null) { // bad, but true try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } return ret[0]; }
From source file:net.myrrix.client.ClientRecommender.java
@Override public float[] estimatePreferences(long userID, long... itemIDs) throws TasteException { StringBuilder urlPath = new StringBuilder(); urlPath.append("/estimate/"); urlPath.append(userID);/*from w w w . j a v a 2s. c o m*/ for (long itemID : itemIDs) { urlPath.append('/').append(itemID); } TasteException savedException = null; for (HostAndPort replica : choosePartitionAndReplicas(userID)) { HttpURLConnection connection = null; try { connection = buildConnectionToReplica(replica, urlPath.toString(), "GET"); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_OK: BufferedReader reader = IOUtils.bufferStream(connection.getInputStream()); try { float[] result = new float[itemIDs.length]; for (int i = 0; i < itemIDs.length; i++) { result[i] = LangUtils.parseFloat(reader.readLine()); } return result; } finally { reader.close(); } case HttpURLConnection.HTTP_UNAVAILABLE: throw new NotReadyException(); default: throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage()); } } catch (TasteException te) { log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString()); savedException = te; } catch (IOException ioe) { log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString()); savedException = new TasteException(ioe); } finally { if (connection != null) { connection.disconnect(); } } } throw savedException; }
From source file:org.jmxtrans.embedded.output.CopperEggWriter.java
public void one_set(String mg_name, List<QueryResult> counters) { HttpURLConnection urlCxn = null; URL newurl = null;/* w w w . j a va 2 s . c om*/ try { newurl = new URL(url_str + "/samples/" + mg_name + ".json"); if (proxy == null) { urlCxn = (HttpURLConnection) newurl.openConnection(); } else { urlCxn = (HttpURLConnection) newurl.openConnection(proxy); } if (urlCxn != null) { urlCxn.setRequestMethod("POST"); urlCxn.setDoInput(true); urlCxn.setDoOutput(true); urlCxn.setReadTimeout(coppereggApiTimeoutInMillis); urlCxn.setRequestProperty("content-type", "application/json; charset=utf-8"); urlCxn.setRequestProperty("Authorization", "Basic " + basicAuthentication); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception: one_set: failed to connect to CopperEgg Service '{}' with proxy {}", newurl, proxy, e); return; } if (urlCxn != null) { try { cue_serialize(counters, urlCxn.getOutputStream()); int responseCode = urlCxn.getResponseCode(); if (responseCode != 200) { logger.warn("one_set: Failure {}: {} to send result to CopperEgg service {}", responseCode, urlCxn.getResponseMessage(), newurl); } try { InputStream in = urlCxn.getInputStream(); IoUtils2.copy(in, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(in); InputStream err = urlCxn.getErrorStream(); if (err != null) { IoUtils2.copy(err, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(err); } } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Execption one_set: Write-Exception flushing http connection", e); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Execption: one_set: Failure to send result to CopperEgg Service '{}' with proxy {}", newurl, proxy, e); } } }
From source file:connection.HttpReq.java
@Override protected String doInBackground(HttpReqPkg... params) { URL url;/* w w w .j av a 2 s. c o m*/ BufferedReader reader = null; String username = params[0].getUsername(); String password = params[0].getPassword(); String authStringEnc = null; if (username != null && password != null) { String authString = username + ":" + password; byte[] authEncBytes; authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT); authStringEnc = new String(authEncBytes); } String uri = params[0].getUri(); if (params[0].getMethod().equals("GET")) { uri += "?" + params[0].getEncodedParams(); } try { StringBuilder sb; // create the HttpURLConnection url = new URL(uri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (authStringEnc != null) { connection.setRequestProperty("Authorization", "Basic " + authStringEnc); } if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT") || params[0].getMethod().equals("DELETE")) { // enable writing output to this url connection.setDoOutput(true); } if (params[0].getMethod().equals("POST")) { connection.setRequestMethod("POST"); } else if (params[0].getMethod().equals("GET")) { connection.setRequestMethod("GET"); } else if (params[0].getMethod().equals("PUT")) { connection.setRequestMethod("PUT"); } else if (params[0].getMethod().equals("DELETE")) { connection.setRequestMethod("DELETE"); } // give it x seconds to respond connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); connection.setRequestProperty("Content-Type", contentType); for (int i = 0; i < headerMap.size(); i++) { connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i)); } connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length); connection.connect(); if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) { OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); String httpParams = params[0].getEncodedParams(); if (contentType.equals(OptimusHTTP.CONTENT_TYPE_JSON)) { httpParams = httpParams.replace("=", " "); } writer.write(httpParams); writer.flush(); writer.close(); } // read the output from the server InputStream in; resCode = connection.getResponseCode(); resMsg = connection.getResponseMessage(); if (resCode != HttpURLConnection.HTTP_OK) { in = connection.getErrorStream(); } else { in = connection.getInputStream(); } reader = new BufferedReader(new InputStreamReader(in)); sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } sb.append(resCode).append(" : ").append(resMsg); return sb.toString(); } catch (Exception e) { listener.onFailure(Integer.toString(resCode) + " : " + resMsg); e.printStackTrace(); } finally { // close the reader; this can throw an exception too, so // wrap it in another try/catch block. if (reader != null) { try { reader.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return null; }
From source file:iracing.webapi.IracingWebApi.java
private String doGetRequest(boolean needForumCookie, String url, String userAgent) throws IOException, LoginException { if (!cookieMap.containsKey(JSESSIONID)) { if (login() != LoginResponse.Success) return null; }/*from w w w . j a v a 2 s .co m*/ if (needForumCookie && !cookieMap.containsKey(JFORUMSESSIONID)) { if (!forumLoginAndGetCookie()) return null; } String output = null; try { // Make a connection URL oUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) oUrl.openConnection(); conn.addRequestProperty(COOKIE, cookie); // request to have the response gzipped (bringing a 3.5Mb response down to 175kb) conn.addRequestProperty("Accept-Encoding", "gzip"); if (userAgent != null) conn.addRequestProperty("User-Agent", userAgent); // conn.setDoInput(true); // conn.setUseCaches(false); // conn.setInstanceFollowRedirects(false); // HttpURLConnection.setFollowRedirects(false); // logger.debug("opening connection to " + url.getFile()); conn.connect(); if (isMaintenancePage(conn)) return null; // Ensure we got the HTTP 200 response code int responseCode = conn.getResponseCode(); if (responseCode != 200) { throw new Exception(String.format("Received the response code %d from the URL %s : %s", responseCode, url, conn.getResponseMessage())); } // Read the response output = getResponseText(conn); // System.out.println(output); conn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } return output; }
From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java
/** * Fetches a file via http protocol.//from w w w . ja va 2 s .c o m * * @param importSource * @param ft * @return fetched file as byte[] * @throws IdentifierNotRecognisedException * @throws RuntimeException * @throws AccessException */ private byte[] fetchHttpFile(FullTextVO ft) throws IdentifierNotRecognisedException, RuntimeException, AccessException { URLConnection conn; byte[] input = null; try { conn = ProxyHelper.openConnection(ft.getFtUrl()); HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); switch (responseCode) { case 503: // request was not processed by source this.logger.warn("Import source " + this.currentSource.getName() + "did not provide file."); throw new FormatNotAvailableException(ft.getFtLabel()); case 302: String alternativeLocation = conn.getHeaderField("Location"); ft.setFtUrl(new URL(alternativeLocation)); return fetchHttpFile(ft); case 200: this.logger.info("Source responded with 200."); GetMethod method = new GetMethod(ft.getFtUrl().toString()); HttpClient client = new HttpClient(); ProxyHelper.executeMethod(client, method); input = method.getResponseBody(); httpConn.disconnect(); break; case 403: throw new AccessException("Access to url " + this.currentSource.getName() + " is restricted."); default: throw new RuntimeException("An error occurred during importing from external system: " + responseCode + ": " + httpConn.getResponseMessage()); } } catch (AccessException e) { this.logger.error("Access denied.", e); throw new AccessException(this.currentSource.getName()); } catch (Exception e) { throw new RuntimeException(e); } return input; }