List of usage examples for java.net HttpURLConnection getInputStream
public InputStream getInputStream() throws IOException
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);// w w w.j ava2 s .co 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:eu.eexcess.ddb.recommender.PartnerConnector.java
/** * Opens a HTTP connection, gets the response and converts into to a String. * //from w ww . j a v a 2s . c o m * @param urlStr Servers URL * @param properties Keys and values for HTTP request properties * @return Servers response * @throws IOException If connection could not be established or response code is !=200 */ public static String httpGet(String urlStr, HashMap<String, String> properties) throws IOException { if (properties == null) { properties = new HashMap<String, String>(); } // open HTTP connection with URL URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // set properties if any do exist for (String key : properties.keySet()) { conn.setRequestProperty(key, properties.get(key)); } // test if request was successful (status 200) if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); } // buffer the result into a string InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "UTF-8"); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); isr.close(); conn.disconnect(); return sb.toString(); }
From source file:io.webfolder.cdp.ChromiumDownloader.java
public static ChromiumVersion getLatestVersion() { String url = DOWNLOAD_HOST;//from w w w . j a v a2 s . c om if (WINDOWS) { url += "/Win_x64/LAST_CHANGE"; } else if (LINUX) { url += "/Linux_x64/LAST_CHANGE"; } else if (MAC) { url += "/Mac/LAST_CHANGE"; } else { throw new CdpException("Unsupported OS found - " + OS); } try { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); if (conn.getResponseCode() != 200) { throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage()); } String result = null; try (Scanner s = new Scanner(conn.getInputStream())) { s.useDelimiter("\\A"); result = s.hasNext() ? s.next() : ""; } return new ChromiumVersion(Integer.parseInt(result)); } catch (IOException e) { throw new CdpException(e); } }
From source file:com.memetix.gun4j.GunshortenAPI.java
protected static JSONObject post(final String serviceUrl, final String paramsString) throws Exception { final URL url = new URL(serviceUrl); final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (referrer != null) uc.setRequestProperty("referer", referrer); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING); uc.setRequestProperty("Accept-Charset", ENCODING); uc.setRequestMethod("POST"); uc.setDoOutput(true);/*from w w w . ja v a 2 s . c o m*/ final PrintWriter pw = new PrintWriter(uc.getOutputStream()); pw.write(paramsString); pw.close(); uc.getOutputStream().close(); try { final int responseCode = uc.getResponseCode(); final String result = inputStreamToString(uc.getInputStream()); if (responseCode != 200) { throw new Exception("Error from Gunshorten API: " + result); } return parseJSON(result); } finally { uc.getInputStream().close(); if (uc.getErrorStream() != null) { uc.getErrorStream().close(); } } }
From source file:com.example.android.didyoufeelit.Utils.java
/** * Make an HTTP request to the given URL and return a String as the response. *///from ww w .j a v a 2 s. c o m private static String makeHttpRequest(URL url) throws IOException { String jsonResponse = ""; // If the URL is null, then return early. if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000 /* milliseconds */); urlConnection.setConnectTimeout(15000 /* milliseconds */); urlConnection.setRequestMethod("GET"); urlConnection.connect(); // If the request was successful (response code 200), // then read the input stream and parse the response. if (urlConnection.getResponseCode() == 200) { inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } } return jsonResponse; }
From source file:org.lightjason.agentspeak.action.builtin.rest.IBaseRest.java
/** * creates a HTTP connection and reads the data * * @param p_url url//from w w w. j av a 2s .c o m * @return url data * * @throws IOException is thrown on connection errors */ @Nonnull private static String httpdata(@Nonnull final String p_url) throws IOException { final HttpURLConnection l_connection = (HttpURLConnection) new URL(p_url).openConnection(); // follow HTTP redirects l_connection.setInstanceFollowRedirects(true); // set a HTTP-User-Agent if not exists l_connection.setRequestProperty("User-Agent", (System.getProperty("http.agent") == null) || (System.getProperty("http.agent").isEmpty()) ? CCommon.PACKAGEROOT + CCommon.configuration().getString("version") : System.getProperty("http.agent")); // read stream data final InputStream l_stream = l_connection.getInputStream(); final String l_return = CharStreams.toString(new InputStreamReader(l_stream, (l_connection.getContentEncoding() == null) || (l_connection.getContentEncoding().isEmpty()) ? Charsets.UTF_8 : Charset.forName(l_connection.getContentEncoding()))); Closeables.closeQuietly(l_stream); return l_return; }
From source file:imageLines.ImageHelpers.java
/**Read a jpeg image from a url into a BufferedImage*/ public static BufferedImage readAsBufferedImage(URL imageURL, String cookieVal) { InputStream i = null;// ww w .j a va2 s . c o m try { HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection(); conn.setRequestProperty("Cookie", cookieVal); int responseCode = conn.getResponseCode(); if (responseCode == 200 || responseCode == 304) { System.out.print("good response" + responseCode + "\n"); } else { System.out.print("bad response " + responseCode + "\n"); } i = conn.getInputStream(); //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(i); BufferedImage bi = ImageIO.read(i);//decoder.decodeAsBufferedImage(); return bi; } catch (Exception e) { System.out.println(e); return null; } finally { try { if (i != null) i.close(); } catch (IOException ex) { } } }
From source file:com.clevertrail.mobile.viewtrail.Object_TrailArticle.java
private static int loadTrailArticle_helper(Activity activity, String sTrailName) { String sResponseLine = ""; //sanity check if (sTrailName == null || sTrailName == "") return R.string.error_notrailname; //connect to clevertrail.com to get trail article HttpURLConnection urlConnection = null; try {//from w w w.j a v a 2s . c om String requestURL = String.format("http://clevertrail.com/ajax/handleGetArticleJSONByName.php?name=%s", Uri.encode(sTrailName)); URL url = new URL(requestURL); urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader r = new BufferedReader(new InputStreamReader(in)); //trail article in json format sResponseLine = r.readLine(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return R.string.error_contactingclevertrail; } catch (IOException e) { // TODO Auto-generated catch block // could not connect to clevertrail.com e.printStackTrace(); return R.string.error_contactingclevertrail; } finally { if (urlConnection != null) urlConnection.disconnect(); } JSONObject json = null; try { if (sResponseLine != "") json = new JSONObject(sResponseLine); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); return R.string.error_corrupttrailinfo; } //now that we have the latest trail information, mark it as unsaved Object_TrailArticle.bSaved = false; // if json is null, we might not have internet activity so check saved // files if (json == null) { Database_SavedTrails db = new Database_SavedTrails(activity); db.openToRead(); String jsonString = db.getJSONString(sTrailName); try { json = new JSONObject(jsonString); // if we found the json object in the db, mark it as saved if (json != null) { Object_TrailArticle.bSaved = true; } } catch (JSONException e) { return R.string.error_corrupttrailinfo; } db.close(); } if (json != null) { Object_TrailArticle.createFromJSON(sTrailName, json); Object_TrailArticle.jsonText = sResponseLine; //after loading the data, launch the activity to actually view the trail Intent i = new Intent(mActivity, Activity_ViewTrail.class); mActivity.startActivity(i); return 0; } return R.string.error_corrupttrailinfo; }
From source file:com.openforevent.main.UserPosition.java
public static Map<String, Object> userPositionByIP(DispatchContext ctx, Map<String, ? extends Object> context) throws IOException { URL url = new URL("http://api.ipinfodb.com/v3/ip-city/?" + "key=" + ipinfodb_key + "&" + "&ip=" + default_ip + "&format=xml"); //URL url = new URL("http://ipinfodb.com/ip_query.php"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true);/*from ww w . j a v a2s. c om*/ urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode = urlConnection.getResponseCode(); InputStream inputStream; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); String theString = writer.toString(); Debug.logInfo("Get user position by IP stream is = ", theString); Map<String, Object> paramOut = FastMap.newInstance(); paramOut.put("stream", theString); return paramOut; }
From source file:Main.java
public static String httpPost(String urlStr, List<NameValuePair> params) { String paramsEncoded = ""; if (params != null) { paramsEncoded = URLEncodedUtils.format(params, "UTF-8"); }//from ww w .jav a 2 s.c o m String result = null; URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; try { url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Charset", "utf-8"); DataOutputStream dop = new DataOutputStream(connection.getOutputStream()); dop.writeBytes(paramsEncoded); dop.flush(); dop.close(); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; }