List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:Authentication.DinserverAuth.java
public static boolean Login(String nick, String pass, Socket socket) throws IOException { boolean logged = false; JSONObject authRequest = new JSONObject(); authRequest.put("username", nick); authRequest.put("auth_id", pass); String query = "http://127.0.0.1:5000/token"; URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000);// ww w . ja v a 2 s.c o m conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(authRequest.toString().getBytes(Charset.forName("UTF-8"))); os.close(); String output = new String(); StringBuilder sb = new StringBuilder(); int HttpResult = conn.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { output = IOUtils.toString(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); } else { System.out.println(conn.getResponseMessage()); } JSONObject jsonObject = new JSONObject(output); logged = jsonObject.getBoolean("ok"); conn.disconnect(); if (logged) { if (DinserverMaster.addUser(nick, socket)) { System.out.println("User " + nick + " logged in"); } else { logged = false; } } return logged; }
From source file:net.dian1.player.download.DownloadTask.java
public static Boolean downloadFile(DownloadJob job) throws IOException { // TODO rewrite to apache client PlaylistEntry mPlaylistEntry = job.getPlaylistEntry(); String mDestination = job.getDestination(); Music engineMusic = mPlaylistEntry.getMusic(); String url = engineMusic.getFirstMusicNetUrl(); if (TextUtils.isEmpty(url)) { engineMusic = requestMusicDetail(engineMusic.getId()); url = engineMusic.getFirstMusicNetUrl(); job.getPlaylistEntry().setMusic(engineMusic); }//from w ww. ja v a2s . c om //url = "http://room2.5dian1.net/??1/15.?.mp3"; if (TextUtils.isEmpty(url)) { return false; } URL u = new URL(url); HttpURLConnection connection = (HttpURLConnection) u.openConnection(); connection.setRequestMethod("GET"); //c.setDoOutput(true); //c.setDoInput(true); connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("Content-Type", "audio/mpeg"); connection.connect(); job.setTotalSize(connection.getContentLength()); Log.i(Dian1Application.TAG, "creating file"); String path = DownloadHelper.getAbsolutePath(mPlaylistEntry, mDestination); String fileName = DownloadHelper.getFileName(mPlaylistEntry, job.getFormat()); try { // Create multiple directory boolean success = (new File(path)).mkdirs(); if (success) { Log.i(Dian1Application.TAG, "Directory: " + path + " created"); } } catch (Exception e) {//Catch exception if any Log.e(Dian1Application.TAG, "Error creating folder", e); return false; } File outFile = new File(path, fileName); FileOutputStream fos = new FileOutputStream(outFile); InputStream in = connection.getInputStream(); if (in == null) { // When InputStream is a NULL fos.close(); return false; } byte[] buffer = new byte[1024]; int lenght = 0; while ((lenght = in.read(buffer)) > 0) { fos.write(buffer, 0, lenght); job.setDownloadedSize(job.getDownloadedSize() + lenght); } fos.close(); mPlaylistEntry.getMusic().getFirstMusicUrlInfo().setLocalUrl(outFile.getAbsolutePath()); //downloadCover(job); return true; }
From source file:org.coffeeking.controller.service.util.ConnectedCupServiceUtils.java
public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext, boolean fireAndForgot) throws DeviceManagementException { String responseMsg = ""; String urlString = ConnectedCupConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext; if (log.isDebugEnabled()) { log.debug(urlString);//from www.j av a 2s.c om } if (!fireAndForgot) { HttpURLConnection httpConnection = getHttpConnection(urlString); try { httpConnection.setRequestMethod(HttpMethod.GET); } catch (ProtocolException e) { String errorMsg = "Protocol specific error occurred when trying to set method to GET" + " for:" + urlString; log.error(errorMsg); throw new DeviceManagementException(errorMsg, e); } responseMsg = readResponseFromGetRequest(httpConnection); } else { CloseableHttpAsyncClient httpclient = null; try { httpclient = HttpAsyncClients.createDefault(); httpclient.start(); HttpGet request = new HttpGet(urlString); final CountDownLatch latch = new CountDownLatch(1); Future<HttpResponse> future = httpclient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse httpResponse) { latch.countDown(); } @Override public void failed(Exception e) { latch.countDown(); } @Override public void cancelled() { latch.countDown(); } }); latch.await(); } catch (InterruptedException e) { if (log.isDebugEnabled()) { log.debug("Sync Interrupted"); } } finally { try { if (httpclient != null) { httpclient.close(); } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed on close"); } } } } return responseMsg; }
From source file:com.meetingninja.csse.database.TaskDatabaseAdapter.java
public static void getTask(Task t) throws JsonParseException, JsonMappingException, IOException { // Server URL setup String _url = getBaseUri().appendPath(t.getID()).build().toString(); URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.GET); addRequestHeader(conn, false);/*from ww w .j av a 2s.co m*/ // Get server response int responseCode = conn.getResponseCode(); String response = getServerResponse(conn); // Initialize ObjectMapper // List<Task> taskList = new ArrayList<Task>(); final JsonNode taskNode = MAPPER.readTree(response); // if(taskArray.isArray()){ // for(final JsonNode taskNode : taskArray){ parseTask(taskNode, t); // if(t!=null){ // taskList.add(t); // } // } // } conn.disconnect(); // return void; }
From source file:com.arthurpitman.common.HttpUtils.java
/** * Connects to an HTTP resource using the post method. * @param url the URL to connect to./*from www . j a va 2s . c o m*/ * @param requestProperties optional request properties, <code>null</code> if not required. * @param postData the data to post. * @return the resulting {@link HttpURLConnection}. * @throws IOException */ public static HttpURLConnection connectPost(final String url, final RequestProperty[] requestProperties, final byte[] postData) throws IOException { // setup connection HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod(POST_METHOD); // send the post form connection.setFixedLengthStreamingMode(postData.length); addRequestProperties(connection, requestProperties); OutputStream outStream = connection.getOutputStream(); outStream.write(postData); outStream.close(); return connection; }
From source file:com.uniteddev.Unity.Downloader.java
public static HttpURLConnection setupHTTP(String fileurl) throws MalformedURLException, IOException { HttpURLConnection httpConnection = (HttpURLConnection) new URL(fileurl).openConnection(); httpConnection.setRequestMethod("GET"); httpConnection.setRequestProperty("Content-Type", "application/java-archive"); httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31"); return httpConnection; }
From source file:core.Utility.java
private static ArrayList<String> getSynonymsWiktionary(String _word) throws MalformedURLException, IOException { ArrayList<String> _list = new ArrayList(); try {//www. j a va 2s . c o m URL url = new URL("http://www.igrec.ca/project-files/wikparser/wikparser.php?word=" + _word + "&query=syn&lang=en"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; while ((output = br.readLine()) != null) { boolean isEmpty = output.contains("No listed synonyms.") || output.contains("ERROR: The Wiktionary API did not return a page for that word."); if (isEmpty) { conn.disconnect(); return _list; } else { String[] arr = output.trim().split(" "); for (String s : arr) { if (s.length() > 2) { _list.add(s); } } } } conn.disconnect(); } catch (MalformedURLException e) { throw e; } catch (IOException e) { throw e; } return _list; }
From source file:gov.nasa.arc.geocam.geocam.HttpPost.java
public static int post(String url, JSONObject json, String username, String password) throws IOException { HttpURLConnection conn = createConnection(url, username, password); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "application/json"); byte[] jsonBytes = json.toString().getBytes("UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(jsonBytes.length)); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(jsonBytes);/* w w w . ja va 2s. c om*/ out.flush(); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048); for (String line = reader.readLine(); line != null; line = reader.readLine()) { } out.close(); int responseCode = 0; responseCode = conn.getResponseCode(); return responseCode; }
From source file:com.ecofactor.qa.automation.platform.util.FileUtil.java
/** * Download Mobile Zip File from jenkinsosx.ecofactor.com * @param webURL the web url/*from w ww . j a v a 2 s . com*/ * @param destinationPath the destination path */ public static void downloadFileFromURL(final String webURL, final String destinationPath) { LogUtil.setLogString(new StringBuilder("Download File from location :").append(webURL).toString(), true); try { final URL url = new URL(webURL); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); final InputStream inStream = connection.getInputStream(); final FileOutputStream outStream = new FileOutputStream(new File(destinationPath)); final byte[] buf = new byte[1024]; int inByte = inStream.read(buf); while (inByte >= 0) { outStream.write(buf, 0, inByte); inByte = inStream.read(buf); } outStream.flush(); outStream.close(); } catch (Exception e) { LOGGER.error("Error in download file", e); } }
From source file:com.example.admin.processingboilerplate.JsonIO.java
public static StringBuilder loadString(String url) { StringBuilder sb = new StringBuilder(); try {/* w w w. j av a2 s . c o m*/ URLConnection uc = (new URL(url)).openConnection(); HttpURLConnection con = url.startsWith("https") ? (HttpsURLConnection) uc : (HttpURLConnection) uc; try { con.setReadTimeout(6000); con.setConnectTimeout(6000); con.setRequestMethod("GET"); con.setDoInput(true); con.setRequestProperty("User-Agent", USER_AGENT); sb = load(con); } catch (IOException e) { Log.e("loadJson", e.getMessage(), e); } finally { con.disconnect(); } } catch (IOException e) { Log.e("loadJson", e.getMessage(), e); } return sb; }