List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java
/** * send a HTTP POST request//from ww w.j a va 2s. c o m * @param param * @param input_url * @return */ public static String POST(String param, String input_url) { try { URL url = new URL(input_url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/xml"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); PrintWriter xmlOut = new PrintWriter(con.getOutputStream()); xmlOut.write(param); xmlOut.flush(); BufferedReader response = new BufferedReader(new InputStreamReader(con.getInputStream())); String result = ""; String line; while ((line = response.readLine()) != null) { result += "\n" + line; } return result.toString(); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:com.vinexs.tool.NetworkManager.java
public static void haveInternet(Context context, final OnInternetResponseListener listener) { if (!haveNetwork(context)) { listener.onResponsed(false);/*from www .j a 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:de.Keyle.MyPet.api.Util.java
public static String readUrlContent(String address, int timeout) throws IOException { StringBuilder contents = new StringBuilder(2048); BufferedReader br = null;/* w w w. ja va 2 s. co m*/ try { URL url = new URL(address); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setConnectTimeout(timeout); huc.setReadTimeout(timeout); huc.setRequestMethod("GET"); huc.connect(); br = new BufferedReader(new InputStreamReader(huc.getInputStream())); String line; while ((line = br.readLine()) != null) { contents.append(line); } } finally { try { if (br != null) { br.close(); } } catch (Exception e) { e.printStackTrace(); } } return contents.toString(); }
From source file:net.kourlas.voipms_sms.Utils.java
/** * Retrieves a JSON object from the specified URL. * <p/>//from ww w.j a va 2 s .com * Note that this is a blocking method; it should not be called from the URI thread. * * @param urlString The URL to retrieve the JSON from. * @return The JSON object at the specified URL. * @throws IOException if a connection to the server could not be established. * @throws JSONException if the server did not return valid JSON. */ public static JSONObject getJson(String urlString) throws IOException, JSONException { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000); connection.setConnectTimeout(15000); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuilder data = new StringBuilder(); String newLine = System.getProperty("line.separator"); String line; while ((line = reader.readLine()) != null) { data.append(line); data.append(newLine); } reader.close(); return new JSONObject(data.toString()); }
From source file:com.googlecode.osde.internal.igoogle.IgCredentials.java
/** * Makes a HTTP POST request for authentication. * * @param emailUserName the name of the user * @param password the password of the user * @param loginTokenOfCaptcha CAPTCHA token (Optional) * @param loginCaptchaAnswer answer of CAPTCHA token (Optional) * @return http response as a String//from www . j a v a2s.com * @throws IOException */ // TODO: Refactor requestAuthentication() utilizing HttpPost. private static String requestAuthentication(String emailUserName, String password, String loginTokenOfCaptcha, String loginCaptchaAnswer) throws IOException { // Prepare connection. URL url = new URL(URL_GOOGLE_LOGIN); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); logger.fine("url: " + url); // Form the POST params. StringBuilder params = new StringBuilder(); params.append("Email=").append(emailUserName).append("&Passwd=").append(password) .append("&source=OSDE-01&service=ig&accountType=HOSTED_OR_GOOGLE"); if (loginTokenOfCaptcha != null) { params.append("&logintoken=").append(loginTokenOfCaptcha); } if (loginCaptchaAnswer != null) { params.append("&logincaptcha=").append(loginCaptchaAnswer); } // Send POST via output stream. OutputStream outputStream = null; try { outputStream = urlConnection.getOutputStream(); outputStream.write(params.toString().getBytes(IgHttpUtil.ENCODING)); outputStream.flush(); } finally { if (outputStream != null) { outputStream.close(); } } // Retrieve response. // TODO: Should the caller of this method need to know the responseCode? int responseCode = urlConnection.getResponseCode(); logger.fine("responseCode: " + responseCode); InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ? urlConnection.getInputStream() : urlConnection.getErrorStream(); logger.fine("inputStream: " + inputStream); try { String response = IOUtils.toString(inputStream, IgHttpUtil.ENCODING); return response; } finally { if (inputStream != null) { inputStream.close(); } } }
From source file:com.avinashbehera.sabera.network.HttpClient.java
public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) { URL sendUrl;/*from w w w .j ava 2s . c o m*/ try { sendUrl = new URL(url); } catch (MalformedURLException e) { Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL"); return null; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) sendUrl.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setChunkedStreamingMode(1024); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + ""); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); //writer.write(getPostDataStringfromJsonObject(jsonObjSend)); Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString()); //writer.write(jsonObjSend.toString()); writer.write(String.valueOf(jsonObjSend)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); Log.d(TAG, "responseCode = " + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { Log.d(TAG, "responseCode = HTTP OK"); InputStream instream = conn.getInputStream(); String resultString = convertStreamToString(instream); instream.close(); Log.d(TAG, "resultString = " + resultString); //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]" // Transform the String into a JSONObject JSONParser parser = new JSONParser(); JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return null; }
From source file:mashberry.com500px.util.Api_Parser.java
/******************************************************************************* * //from ww w . j a v a 2 s . co m * ( ) * *******************************************************************************/ public static String get_first_detail(final String url_feature, final int url_image_size, final String url_category, final int url_page, int image_no) { String returnStr = "success"; String urlStr = DB.Get_Photo_Url + "?feature=" + url_feature + "&image_size=" + url_image_size + "&only=" + getCategoryName(url_category) + "&page=" + url_page + "&consumer_key=" + Var.consumer_key + "&rpp=" + image_no; try { URL url = new URL(urlStr); URLConnection uc = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) uc; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setConnectTimeout(10000); httpConn.setRequestMethod("GET"); httpConn.connect(); int response = httpConn.getResponseCode(); Main.progressBar_process(50); if (response == HttpURLConnection.HTTP_OK) { InputStream in = httpConn.getInputStream(); String smallImageOpt = "3"; // (8 1/8 ) String largeImageOpt = "0"; String userPictureOpt = "8"; String result = convertStreamToString(in); JSONObject jObject = new JSONObject(result); JSONArray jsonArray = jObject.getJSONArray("photos"); Main.progressBar_process(75); if (jsonArray.length() == 0) { returnStr = "no results"; } else { for (int i = 0; i < jsonArray.length(); i++) { Var.categoryArr.add(jsonArray.getJSONObject(i).getString("category")); Var.idArr.add(jsonArray.getJSONObject(i).getString("id")); String smallImage = jsonArray.getJSONObject(i).getString("image_url"); String largeImage = largeImageOpt + smallImage.substring(0, smallImage.lastIndexOf(".jpg") - 1) + "4.jpg"; Var.imageSmall_urlArr.add(smallImageOpt + smallImage); Var.imageLarge_urlArr.add(largeImage); Var.nameArr.add(jsonArray.getJSONObject(i).getString("name")); Var.ratingArr.add(jsonArray.getJSONObject(i).getString("rating")); JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user"); Var.user_firstnameArr.add(jsonuser.getString("firstname")); Var.user_fullnameArr.add(jsonuser.getString("fullname")); Var.user_lastnameArr.add(jsonuser.getString("lastname")); Var.user_upgrade_statusArr.add(jsonuser.getString("upgrade_status")); Var.user_usernameArr.add(jsonuser.getString("username")); Var.user_userpic_urlArr.add(userPictureOpt + jsonuser.getString("userpic_url")); Main.progressBar_process(75 + (15 * i / jsonArray.length())); } } // Log.i("Main", "urlStr " +urlStr); // Log.i("Main", "url_feature " +url_feature); // Log.i("Main", "categoryArr " +Var.categoryArr); // Log.i("Main", "idArr " +Var.idArr); // Log.i("Main", "imageLarge_urlArr " +Var.imageLarge_urlArr); // Log.i("Main", "nameArr " +Var.nameArr); // Log.i("Main", "ratingArr " +Var.ratingArr); // Log.i("Main", "user_firstnameArr " +Var.user_firstnameArr); // Log.i("Main", "user_fullnameArr " +Var.user_fullnameArr); // Log.i("Main", "user_lastnameArr " +Var.user_lastnameArr); // Log.i("Main", "user_upgrade_statusArr " +Var.user_upgrade_statusArr); // Log.i("Main", "user_usernameArr " +Var.user_usernameArr); // Log.i("Main", "user_userpic_urlArr " +Var.user_userpic_urlArr); } else { returnStr = "not response"; return returnStr; } } catch (Exception e) { e.printStackTrace(); returnStr = "not response"; return returnStr; } return returnStr; }
From source file:com.createtank.payments.coinbase.RequestClient.java
private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry, String accessToken) throws IOException, UnsupportedRequestVerbException { if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) { throw new UnsupportedRequestVerbException(); }/*from www .java2 s .co m*/ if (api.allowSecure()) { HttpClient client = HttpClientBuilder.create().build(); String url = BASE_URL + method; HttpUriRequest request; switch (verb) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; default: throw new RuntimeException("RequestVerb not implemented: " + verb); } ((HttpEntityEnclosingRequestBase) request) .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON)); if (accessToken != null) request.addHeader("Authorization", String.format("Bearer %s", accessToken)); request.addHeader("Content-Type", "application/json"); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = EntityUtils.toString(response.getEntity()); if (responseString.startsWith("[")) { // Is an array responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(responseString); System.out.println(resp.toString()); return resp; } String url = BASE_URL + method; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(verb.name()); conn.addRequestProperty("Content-Type", "application/json"); if (accessToken != null) conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken)); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(json.toString()); writer.flush(); writer.close(); int code = conn.getResponseCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); return call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = getResponseBody(conn.getInputStream()); if (responseString.startsWith("[")) { responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); return (JsonObject) parser.parse(responseString); }
From source file:au.com.tyo.sn.shortener.GooGl.java
private static String post(String url) { HttpURLConnection httpcon = null; try {/*from w w w. j a va2s . co m*/ httpcon = (HttpURLConnection) ((new URL(GOO_GL_REQUEST_URL).openConnection())); httpcon.setDoOutput(true); httpcon.setRequestProperty("Content-Type", "application/json"); httpcon.setRequestProperty("Accept", "application/json"); httpcon.setRequestMethod("POST"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } byte[] outputBytes = { 0 }; OutputStream os = null; InputStream is = null; BufferedReader in = null; StringBuilder text = new StringBuilder(); try { outputBytes = ("{'longUrl': \"" + url + "\"}").getBytes("UTF-8"); httpcon.setRequestProperty("Content-Length", Integer.toString(outputBytes.length)); httpcon.connect(); os = httpcon.getOutputStream(); os.write(outputBytes); is = httpcon.getInputStream(); in = new BufferedReader(new InputStreamReader(is, "UTF-8")); if (in != null) { // get page text String line; while ((line = in.readLine()) != null) { text.append(line); text.append("\n"); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (os != null) os.close(); if (is != null) is.close(); if (in != null) in.close(); } catch (IOException e) { } } return text.toString(); }
From source file:com.github.thorqin.webapi.oauth2.OAuthClient.java
public static AccessToken obtainAccessTokenByCode(String authorityServerUri, String clientId, String clientSecret, String code, String redirectUri, boolean useBasicAuthentication) throws IOException, OAuthException { String rawData = makeObtainAccessTokenByCode(clientId, clientSecret, code, redirectUri, useBasicAuthentication);//from w w w . jav a 2s.c o m String type = "application/x-www-form-urlencoded"; URL u = new URL(authorityServerUri); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true); if (useBasicAuthentication) { String basicAuthentication = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes()); conn.setRequestProperty("Authorization", "Basic " + basicAuthentication); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", type); conn.setRequestProperty("Content-Length", String.valueOf(rawData.length())); try (OutputStream os = conn.getOutputStream()) { os.write(rawData.getBytes()); } try (InputStream is = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(is)) { AccessTokenResponse token = Serializer.fromJson(reader, AccessTokenResponse.class); if (token.error != null) { throw new OAuthException(token.error, token.errorDescription, token.errorUri); } return token; } }