List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.example.admin.processingboilerplate.JsonIO.java
public static StringBuilder loadString(String url) { StringBuilder sb = new StringBuilder(); try {//from ww w.j av a 2s. co 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; }
From source file:com.example.makerecg.NetworkUtilities.java
/** * Connects to the SampleSync test server, authenticates the provided * username and password.//from ww w . ja v a2s .co m * This is basically a standard OAuth2 password grant interaction. * * @param username The server account username * @param password The server account password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String password) { String token = null; try { Log.i(TAG, "Authenticating to: " + AUTH_URI); URL urlToRequest = new URL(AUTH_URI); HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("grant_type", "password")); params.add(new BasicNameValuePair("client_id", "CLIENT_ID")); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } br.close(); // Response body will look something like this: // { // "token_type": "bearer", // "access_token": "0dd18fd38e84fb40e9e34b1f82f65f333225160a", // "expires_in": 3600 // } JSONObject jresp = new JSONObject(new JSONTokener(response)); token = jresp.getString("access_token"); } else { Log.e(TAG, "Error authenticating"); token = null; } } catch (Exception e) { e.printStackTrace(); } finally { Log.v(TAG, "getAuthtoken completing"); } return token; }
From source file:com.android.idearse.Result.java
public static Bitmap getBitmapFromURL(String src) { try {/*from w w w . jav a 2 s .c om*/ URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { e.printStackTrace(); return null; } }
From source file:com.openforevent.main.UserPosition.java
public static Map<String, Object> userLocationProperties(DispatchContext ctx, Map<String, ? extends Object> context) throws IOException { Delegator delegator = ctx.getDelegator(); LocalDispatcher dispatcher = ctx.getDispatcher(); String visitId = (String) context.get("visitId"); if (Debug.infoOn()) { Debug.logInfo("In userLocationProperties", module); }/*w w w . j a va 2 s. c o m*/ // get user coords coordsOfUserPosition(ctx, context); URL url = new URL( "https://graph.facebook.com/search?since=now&limit=4&q=2012-05-07&type=event&access_token=" + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); 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("Facebook stream = ", theString); if (theString.contains("AuthException") == true) { url = new URL("https://graph.facebook.com/oauth/access_token?" + "client_id= 283576871735609&" + "client_secret= 5cf1fe4e531dff8de228bfac61b8fdfa&" + "grant_type=fb_exchange_token&" + "fb_exchange_token=" + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD"); HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection1.setRequestMethod("GET"); urlConnection1.setDoInput(true); urlConnection1.setDoOutput(true); urlConnection1.setUseCaches(false); urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode1 = urlConnection1.getResponseCode(); InputStream inputStream1; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream1 = urlConnection1.getInputStream(); } else { inputStream1 = urlConnection1.getErrorStream(); } StringWriter writer1 = new StringWriter(); IOUtils.copy(inputStream1, writer1, "UTF-8"); String theString1 = writer1.toString(); Debug.logInfo("Facebook stream1 = ", theString1); } Map<String, Object> paramOut = FastMap.newInstance(); paramOut.put("geoName", "aaa"); paramOut.put("abbreviation", "bbb"); return paramOut; }
From source file:Main.java
public static String simplePost(String url, Bundle params, String method) throws MalformedURLException, IOException { OutputStream os;//from w ww . j a v a2s . c om System.setProperty("http.keepAlive", "false"); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent"); conn.setRequestMethod(method); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.setDoInput(true); //conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(encodePostParams(params).getBytes()); os.flush(); String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:com.example.makerecg.NetworkUtilities.java
/** * Perform 2-way sync with the server-side ADSampleFrames. We send a request that * includes all the locally-dirty contacts so that the server can process * those changes, and we receive (and return) a list of contacts that were * updated on the server-side that need to be updated locally. * * @param account The account being synced * @param authtoken The authtoken stored in the AccountManager for this * account//from w w w. j a v a2s. c o m * @param serverSyncState A token returned from the server on the last sync * @param dirtyFrames A list of the frames to send to the server * @return A list of frames that we need to update locally */ public static List<ADSampleFrame> syncSampleFrames(Account account, String authtoken, long serverSyncState, List<ADSampleFrame> dirtyFrames) throws JSONException, ParseException, IOException, AuthenticationException { List<JSONObject> jsonFrames = new ArrayList<JSONObject>(); for (ADSampleFrame frame : dirtyFrames) { jsonFrames.add(frame.toJSONObject()); } JSONArray buffer = new JSONArray(jsonFrames); JSONObject top = new JSONObject(); top.put("data", buffer); // Create an array that will hold the server-side ADSampleFrame // that have been changed (returned by the server). final ArrayList<ADSampleFrame> serverDirtyList = new ArrayList<ADSampleFrame>(); // Send the updated frames data to the server //Log.i(TAG, "Syncing to: " + SYNC_URI); URL urlToRequest = new URL(SYNC_URI); HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "Bearer " + authtoken); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(top.toString(1)); writer.flush(); writer.close(); os.close(); //Log.i(TAG, "body="+top.toString(1)); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { // Our request to the server was successful - so we assume // that they accepted all the changes we sent up, and // that the response includes the contacts that we need // to update on our side... // TODO: Only uploading data for now ... String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } br.close(); //Log.i(TAG, "response="+response); /* final JSONArray serverContacts = new JSONArray(response); Log.d(TAG, response); for (int i = 0; i < serverContacts.length(); i++) { ADSampleFrame rawContact = ADSampleFrame.valueOf(serverContacts.getJSONObject(i)); if (rawContact != null) { serverDirtyList.add(rawContact); } } */ } else { if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in while uploading data"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in sending sample frames: " + responseCode); throw new IOException(); } } return null; }
From source file:com.gallatinsystems.common.util.S3Util.java
public static boolean putObjectAcl(String bucketName, String objectKey, ACL acl, String awsAccessId, String awsSecretKey) throws IOException { final String date = getDate(); final URL url = new URL(String.format(S3_URL, bucketName, objectKey) + "?acl"); final String payload = String.format(PUT_PAYLOAD_ACL, date, acl.toString(), bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); HttpURLConnection conn = null; try {//ww w.jav a 2 s. c o m conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Date", date); conn.setRequestProperty("x-amz-acl", acl.toString()); conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); int status = conn.getResponseCode(); if (status != 200 && status != 201) { log.severe("Error setting ACL for: " + url.toString()); log.severe(IOUtils.toString(conn.getInputStream())); return false; } return true; } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.vinexs.tool.NetworkManager.java
public static void haveInternet(Context context, final OnInternetResponseListener listener) { if (!haveNetwork(context)) { listener.onResponsed(false);//from w w w . ja v a 2 s.c o m return; } Log.d("Network", "Check internet is reachable ..."); new AsyncTask<Void, Integer, Boolean>() { @Override protected Boolean doInBackground(Void... params) { try { InetAddress ipAddr = InetAddress.getByName("google.com"); if (ipAddr.toString().equals("")) { throw new Exception("Cannot resolve host name, no internet behind network."); } HttpURLConnection conn = (HttpURLConnection) new URL("http://google.com/").openConnection(); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(3500); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); DataOutputStream postOutputStream = new DataOutputStream(conn.getOutputStream()); postOutputStream.write('\n'); postOutputStream.close(); conn.disconnect(); Log.d("Network", "Internet is reachable."); return true; } catch (Exception e) { e.printStackTrace(); } Log.d("Network", "Internet is unreachable."); return false; } @Override protected void onPostExecute(Boolean result) { listener.onResponsed(result); } }.execute(); }
From source file:com.melniqw.instagramsdk.Network.java
private static String sendDummyRequest(String url, String body, Request request) throws IOException { HttpURLConnection connection = null; try {// w w w.j a va2 s . c o m connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.setUseCaches(false); connection.setDoInput(true); // connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); if (request == Request.GET) { connection.setDoOutput(false); connection.setRequestMethod("GET"); } else if (request == Request.POST) { connection.setDoOutput(true); connection.setRequestMethod("POST"); } if (REQUEST_ENABLE_COMPRESSION) connection.setRequestProperty("Accept-Encoding", "gzip"); if (request == Request.POST) connection.getOutputStream().write(body.getBytes("utf-8")); int code = connection.getResponseCode(); System.out.println(TAG + " responseCode = " + code); //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation if (code == -1) throw new WrongResponseCodeException("Network error"); // ? 200 //on error can also read error stream from connection. InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192); String encoding = connection.getHeaderField("Content-Encoding"); if (encoding != null && encoding.equalsIgnoreCase("gzip")) inputStream = new GZIPInputStream(inputStream); String response = Utils.convertStreamToString(inputStream); System.out.println(TAG + " response = " + response); return response; } finally { if (connection != null) connection.disconnect(); } }
From source file:com.facebook.fresco.sample.urlsfetcher.ImageUrlsFetcher.java
@Nullable private static String downloadContentAsString(String urlString) throws IOException { InputStream is = null;//from w ww.j ava 2 s. c om try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if (response != HttpStatus.SC_OK) { FLog.e(TAG, "Album request returned %s", response); return null; } is = conn.getInputStream(); return readAsString(is); } finally { if (is != null) { is.close(); } } }