List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:mashberry.com500px.util.Api_Parser.java
/******************************************************************************* * // www . j a v a 2 s . co m * ( ) * *******************************************************************************/ public static String get_second_detail(final int position, final String string, final int url_image_size, final int comments, final int comments_page) { String returnStr = "success"; String urlStr = DB.Get_Photo_Url + "/" + string + "?image_size=" + url_image_size /*+ "&comments=" + comments + "&comments_page=" + comments_page*/ + "&consumer_key=" + Var.consumer_key; try { URL url = new URL(urlStr); URLConnection uc = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) uc; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); httpConn.setConnectTimeout(10000); int response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK) { InputStream in = httpConn.getInputStream(); String userPictureOpt = "8"; String result = convertStreamToString(in); JSONObject jObject = new JSONObject(result); JSONObject jsonObject = jObject.getJSONObject("photo"); // Log.i(TAG, "jsonObject " + jsonObject); Var.detail_nameMap.put(position, jsonObject.getString("name")); Var.detail_locationMap.put(position, jsonObject.getString("location")); Var.detail_ratingMap.put(position, jsonObject.getString("rating")); Var.detail_times_viewedMap.put(position, jsonObject.getString("times_viewed")); Var.detail_votesMap.put(position, jsonObject.getString("votes_count")); Var.detail_favoritesMap.put(position, jsonObject.getString("favorites_count")); Var.detail_descriptionMap.put(position, jsonObject.getString("description")); Var.detail_cameraMap.put(position, jsonObject.getString("camera")); Var.detail_lensMap.put(position, jsonObject.getString("lens")); Var.detail_focal_lengthMap.put(position, jsonObject.getString("focal_length")); Var.detail_isoMap.put(position, jsonObject.getString("iso")); Var.detail_shutter_speedMap.put(position, jsonObject.getString("shutter_speed")); Var.detail_apertureMap.put(position, jsonObject.getString("aperture")); Var.detail_categoryMap.put(position, jsonObject.getString("category")); Var.detail_uploadedMap.put(position, jsonObject.getString("hi_res_uploaded")); Var.detail_takenMap.put(position, jsonObject.getString("taken_at")); Var.detail_licenseTypeMap.put(position, jsonObject.getString("license_type")); JSONObject jsonuser = jsonObject.getJSONObject("user"); Var.detail_user_nameMap.put(position, jsonuser.getString("fullname")); Var.detail_userpicMap.put(position, userPictureOpt + jsonuser.getString("userpic_url")); // ( . .) /*JSONArray jsonArray = jObject.getJSONArray("comments"); for(int i=0 ; i<jsonArray.length() ; i++){ Var.comment_user_id.add(jsonArray.getJSONObject(i).getString("user_id")); Var.comment_body.add(jsonArray.getJSONObject(i).getString("body")); JSONObject jsonuser = jsonArray.getJSONObject(i).getJSONObject("user"); Var.comment_fullname.add(jsonuser.getString("fullname")); Var.comment_userpic_url.add(jsonuser.getString("userpic_url")); }*/ /* Log.i("Main", "feature " +feature); Log.i("Main", "filters " +filters); Log.i("Main", "categoryArr " +Var.categoryArr); Log.i("Main", "idArr " +Var.idArr); Log.i("Main", "image_urlArr " +Var.image_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:gov.nasa.arc.geocam.geocam.HttpPost.java
public static String postFiles(String url, Map<String, String> vars, Map<String, File> files) { try {/*from w ww.j a va 2 s . c o m*/ HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); assembleMultipartFiles(out, vars, files); InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (UnsupportedEncodingException e) { return "Encoding exception: " + e; } catch (IOException e) { return "IOException: " + e; } catch (IllegalStateException e) { return "IllegalState: " + e; } }
From source file:com.baasbox.service.push.providers.GCMServer.java
public static void validateApiKey(String apikey) throws MalformedURLException, IOException, PushInvalidApiKeyException { Message message = new Message.Builder().addData("message", "validateAPIKEY").build(); Sender sender = new Sender(apikey); List<String> deviceid = new ArrayList<String>(); deviceid.add("ABC"); Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); jsonRequest.put(JSON_REGISTRATION_IDS, deviceid); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); }/*from w ww . ja va 2 s .c o m*/ String requestBody = JSONValue.toJSONString(jsonRequest); String url = com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); byte[] bytes = requestBody.getBytes(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "key=" + apikey); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); int status = conn.getResponseCode(); if (status != 200) { if (status == 401) { throw new PushInvalidApiKeyException("Wrong api key"); } if (status == 503) { throw new UnknownHostException(); } } }
From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
public static HttpResponse doGet(String endpoint, Map<String, String> headers) throws IOException { HttpResponse httpResponse;/*from w ww.j a v a 2s. c o m*/ if (endpoint.startsWith("http://")) { URL url = new URL(endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setReadTimeout(30000); // setting headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); conn.setRequestProperty(key, headers.get(key)); } } conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode()); httpResponse.setResponseMessage(conn.getResponseMessage()); } catch (IOException ignored) { rd = new BufferedReader(new InputStreamReader(conn.getErrorStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } httpResponse = new HttpResponse(sb.toString(), conn.getResponseCode()); httpResponse.setResponseMessage(conn.getResponseMessage()); } finally { if (rd != null) { rd.close(); } } return httpResponse; } return null; }
From source file:com.dmsl.anyplace.utils.NetworkUtils.java
public static InputStream downloadHttp(String urlS) throws URISyntaxException, IOException { InputStream is = null;/* ww w .ja va 2 s . co m*/ URL url = new URL(encodeURL(urlS)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); if (response == 200) { is = conn.getInputStream(); } return is; }
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 w w w . j a v a 2 s. com*/ 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:brainleg.app.util.AppWeb.java
/** * Copied from ITNProxy// w w w . j a v a2s. c o m */ private static HttpURLConnection doPost(String url, byte[] bytes) throws IOException { HttpURLConnection connection = (HttpURLConnection) HttpConfigurable.getInstance().openConnection(url); connection.setReadTimeout(60 * 1000); connection.setConnectTimeout(10 * 1000); connection.setRequestMethod(HTTP_POST); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty(HTTP_CONTENT_TYPE, String.format("%s; charset=%s", HTTP_WWW_FORM, ENCODING)); connection.setRequestProperty(HTTP_CONTENT_LENGTH, Integer.toString(bytes.length)); OutputStream out = new BufferedOutputStream(connection.getOutputStream()); try { out.write(bytes); out.flush(); } finally { out.close(); } return connection; }
From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java
private static SSLContext sslContext() { final String property = SettingsManager.settings().ssl(); if (property != null && !property.isEmpty() && !"null".equals(property)) { if ("trustanything".equals(property)) { try { return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()), new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }/*from w w w .j av a2 s . co m*/ }).build(); } catch (Throwable t) { LogsServer.instance().exception(t); } } else { try { String location = property; location = location.equals("compatible") ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt" : location; File cachedPemFile = new File("./pemfile_cached"); boolean remote = location.startsWith("https://") || location.startsWith("http://"); if (remote && cachedPemFile.exists() && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) { location = cachedPemFile.getAbsolutePath(); remote = false; } String pemBlocks = null; if (remote) { HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler .defaultConnection(new URL(location)); remotePemFile.setRequestMethod("GET"); remotePemFile.connect(); pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile)); cachedPemFile.delete(); Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8")); } else { pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())), "utf-8"); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Matcher matcher = pemBlock.matcher(pemBlocks); boolean found = false; while (matcher.find()) { String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", ""); ByteArrayInputStream byteStream = new ByteArrayInputStream( Base64.getDecoder().decode(pemBlock)); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf .generateCertificate(byteStream); String alias = cert.getSubjectX500Principal().getName("RFC2253"); if (alias != null && !keyStore.containsAlias(alias)) { found = true; keyStore.setCertificateEntry(alias, cert); } } if (found) { KeyManagerFactory keyManager = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManager.init(keyStore, null); TrustManagerFactory trustManager = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManager.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); return context; } } catch (Throwable t) { LogsServer.instance().exception(t); } } } return SSLContexts.createSystemDefault(); }
From source file:com.nhncorp.lucy.security.xss.listener.SecurityUtils.java
public static String getContentTypeFromUrlConnection(String strUrl, ContentTypeCacheRepo contentTypeCacheRepo) { // cache ? ?. String result = contentTypeCacheRepo.getContentTypeFromCache(strUrl); //System.out.println("getContentTypeFromCache : " + result); if (StringUtils.isNotEmpty(result)) { return result; }//from w w w . j av a 2s. c om HttpURLConnection con = null; try { URL url = new URL(strUrl); con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("HEAD"); con.setConnectTimeout(1000); con.setReadTimeout(1000); con.connect(); int resCode = con.getResponseCode(); if (resCode != HttpURLConnection.HTTP_OK) { System.err.println("error"); } else { result = con.getContentType(); //System.out.println("content-type from response header: " + result); if (result != null) { contentTypeCacheRepo.addContentTypeToCache(strUrl, new ContentType(result, new Date())); } } } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.disconnect(); } } return result; }
From source file:com.book.jtm.chap03.HttpClientDemo.java
public static void sendRequest(String method, String url) throws IOException { InputStream is = null;/*from w w w . j a v a2s .c o m*/ try { URL newUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) newUrl.openConnection(); // ?10 conn.setReadTimeout(10000); // 15 conn.setConnectTimeout(15000); // ?,GET"GET",post"POST" conn.setRequestMethod("GET"); // ?? conn.setDoInput(true); // ??,???? conn.setDoOutput(true); // Header conn.setRequestProperty("Connection", "Keep-Alive"); // ? List<NameValuePair> paramsList = new ArrayList<NameValuePair>(); paramsList.add(new BasicNameValuePair("username", "mr.simple")); paramsList.add(new BasicNameValuePair("pwd", "mypwd")); writeParams(conn.getOutputStream(), paramsList); // ? conn.connect(); is = conn.getInputStream(); // ? String result = convertStreamToString(is); Log.i("", "### : " + result); } finally { if (is != null) { is.close(); } } }