List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.iStudy.Study.Renren.Util.java
/** * ??http//from ww w . j a v a 2 s .com * * @param url * @param method GET POST * @param params * @return */ public static String openUrl(String url, String method, Bundle params) { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } String response = ""; try { Log.d(LOG_TAG, method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_SDK); if (!method.equals("GET")) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } InputStream is = null; int responseCode = conn.getResponseCode(); if (responseCode == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); } response = read(is); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } return response; }
From source file:com.codelanx.codelanxlib.logging.Debugger.java
/** * Sends a JSON payload to a URL specified by the string parameter * /*from w w w .j ava2 s. com*/ * @since 0.1.0 * @version 0.1.0 * * @param url The URL to report to * @param payload The JSON payload to send via POST * @throws IOException If the sending failed */ private static void send(String url, JSONObject payload) throws IOException { URL loc = new URL(url); HttpURLConnection http = (HttpURLConnection) loc.openConnection(); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/json"); http.setUseCaches(false); http.setDoOutput(true); try (DataOutputStream wr = new DataOutputStream(http.getOutputStream())) { wr.writeBytes(payload.toJSONString()); wr.flush(); } }
From source file:io.jari.geenstijl.API.API.java
public static String postUrl(String url, List<NameValuePair> params, String cheader, boolean refererandorigin) throws IOException { HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection(); http.setRequestMethod("POST"); http.setDoInput(true);/*from ww w .j ava2 s. co m*/ http.setDoOutput(true); if (cheader != null) http.setRequestProperty("Cookie", cheader); if (refererandorigin) { http.setRequestProperty("Referer", "http://www.geenstijl.nl/mt/archieven/2014/01/brein_chanteert_ondertitelaars.html"); http.setRequestProperty("Origin", "http://www.geenstijl.nl"); } OutputStream os = http.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); http.connect(); InputStream in = http.getInputStream(); String encoding = http.getContentEncoding(); encoding = encoding == null ? "UTF-8" : encoding; ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int len = 0; while ((len = in.read(buf)) != -1) { baos.write(buf, 0, len); } return new String(baos.toByteArray(), encoding); }
From source file:ee.ria.xroad.proxy.ProxyMain.java
private static Map<String, DiagnosticsStatus> checkConnectionToTimestampUrl() { Map<String, DiagnosticsStatus> statuses = new HashMap<>(); for (String tspUrl : ServerConf.getTspUrl()) { try {/*from w w w . j a va2 s.co m*/ URL url = new URL(tspUrl); log.info("Checking timestamp server status for url {}", url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setConnectTimeout(DIAGNOSTICS_CONNECTION_TIMEOUT_MS); con.setReadTimeout(DIAGNOSTICS_READ_TIMEOUT_MS); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/timestamp-query"); con.connect(); log.info("Checking timestamp server con {}", con); if (con.getResponseCode() != HttpURLConnection.HTTP_OK) { log.warn("Timestamp check received HTTP error: {} - {}. Might still be ok", con.getResponseCode(), con.getResponseMessage()); statuses.put(tspUrl, new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl)); } else { statuses.put(tspUrl, new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl)); } } catch (Exception e) { log.warn("Timestamp status check failed {}", e); statuses.put(tspUrl, new DiagnosticsStatus(DiagnosticsUtils.getErrorCode(e), LocalTime.now(), tspUrl)); } } return statuses; }
From source file:com.lostad.app.base.util.RequestUtil.java
/** * HTTP??????,??? /* ww w. j a va2s .co m*/ * @param actionUrl * @param params ? key???,value? * @param files * @throws Exception */ public static String postFile(String actionUrl, Map<String, String> params, FormFile[] files, String token) throws Exception { try { String BOUNDARY = "---------7d4a6d158c9"; //? String MULTIPART_FORM_DATA = "multipart/form-data"; URL url = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true);//? conn.setDoOutput(true);//? conn.setUseCaches(false);//?Cache conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); conn.setRequestProperty("token", token); //???? StringBuilder sb = new StringBuilder(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) {//? sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); sb.append(entry.getValue()); sb.append("\r\n"); } } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes());//???? //?? for (FormFile file : files) { StringBuilder split = new StringBuilder(); split.append("--"); split.append(BOUNDARY); split.append("\r\n"); split.append("Content-Disposition: form-data;name=\"" + file.getFormname() + "\";filename=\"" + file.getFilname() + "\"\r\n"); split.append("Content-Type: " + file.getContentType() + "\r\n\r\n"); outStream.write(split.toString().getBytes()); outStream.write(file.getData(), 0, file.getData().length); outStream.write("\r\n".getBytes()); } byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//?? outStream.write(end_data); outStream.flush(); int cah = conn.getResponseCode(); if (cah != 200) throw new RuntimeException("url"); InputStream is = conn.getInputStream(); int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } outStream.close(); conn.disconnect(); return b.toString(); } catch (Exception e) { throw e; } }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Fetches the list of friend data updates from the server * //from w w w . j a va2 s . c o m * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account, String auth_url, String authtoken, long serverSyncState/*Date lastUpdated*/, String type_contact) throws JSONException, ParseException, IOException, AuthenticationException { ArrayList<User> friendList = new ArrayList<User>(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_OPERATION, "sync")); params.add(new BasicNameValuePair(PARAM_SESSIONNAME, sessionName)); if (serverSyncState == 0) params.add(new BasicNameValuePair("modifiedTime", "878925701")); // il y a 14 ans.... else params.add(new BasicNameValuePair("modifiedTime", String.valueOf(serverSyncState))); params.add(new BasicNameValuePair("elementType", type_contact)); // "Accounts,Leads , Contacts... Log.d(TAG, "fetchFriendUpdates"); // params.add(new BasicNameValuePair(PARAM_QUERY, "select firstname,lastname,mobile,email,homephone,phone from Contacts;")); // if (lastUpdated != null) { // final SimpleDateFormat formatter = // new SimpleDateFormat("yyyy/MM/dd HH:mm"); // formatter.setTimeZone(TimeZone.getTimeZone("UTC")); // params.add(new BasicNameValuePair(PARAM_UPDATED, formatter // .format(lastUpdated))); // } // HTTP GET REQUEST URL url = new URL(auth_url + "/webservice.php?" + URLEncodedUtils.format(params, "utf-8")); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setRequestProperty("accept", "application/json"); con.setUseCaches(false); con.setAllowUserInteraction(false); int timeout = 10000; // si tiemout pas assez important la connection echouait =>IOEXception con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); LastFetchOperationStatus = true; if (status == HttpURLConnection.HTTP_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String response = sb.toString(); Log.i(TAG, "--response--"); // <Hack> to bypass vtiger 5.4 webservice bug: int idx = response.indexOf("{\"success"); response = response.substring(idx); Log.i(TAG, response); // </Hack> Log.i(TAG, "--response end--"); JSONObject result = new JSONObject(response); String success = result.getString("success"); Log.i(TAG, "success is" + success); if (success == "true") { Log.i(TAG, result.getString("result")); final JSONObject data = new JSONObject(result.getString("result")); final JSONArray friends = new JSONArray(data.getString("updated")); // == VTiger updated contacts == for (int i = 0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } // == Vtiger contacts deleted === String deleted_contacts = data.getString("deleted"); Log.d(TAG, deleted_contacts); Log.d(TAG, deleted_contacts.substring(deleted_contacts.indexOf("["))); List<String> items = Arrays.asList( deleted_contacts.substring(deleted_contacts.indexOf("[") + 1, deleted_contacts.indexOf("]")) .split("\\s*,\\s*")); for (int ii = 0; ii < items.size(); ii++) { Log.d(TAG, items.get(ii)); if (items.get(ii).startsWith("\"4x")) // this is a contact { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"contact_no\":\"CON1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"3x")) // this is an account { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"account_no\":\"ACC1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"2x")) // this is a lead { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"lead_no\":\"LEA1\"}"); friendList.add(User.valueOf(item)); } } } else { LastFetchOperationStatus = false; // FIXME: else false... // possible error code : //{"success":false,"error":{"code":"AUTHENTICATION_REQUIRED","message":"Authencation required"}} // throw new AuthenticationException(); } } else { if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { LastFetchOperationStatus = false; Log.e(TAG, "Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { LastFetchOperationStatus = false; Log.e(TAG, "Server error in fetching remote contacts: "); throw new IOException(); } } return friendList; }
From source file:net.fenyo.mail4hotspot.service.Browser.java
public static String getHtml(final String target_url, final Cookie[] cookies) throws IOException { // log.debug("RETRIEVING_URL=" + target_url); final URL url = new URL(target_url); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.69.60.6", 3128)); // final HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy); // HttpURLConnection.setFollowRedirects(true); // conn.setRequestProperty("User-agent", "my agent name"); conn.setRequestProperty("Accept-Language", "en-US"); // conn.setRequestProperty(key, value); // allow both GZip and Deflate (ZLib) encodings conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); final String encoding = conn.getContentEncoding(); InputStream is = null;/*from w ww . j a v a 2s . c om*/ // create the appropriate stream wrapper based on the encoding type if (encoding != null && encoding.equalsIgnoreCase("gzip")) is = new GZIPInputStream(conn.getInputStream()); else if (encoding != null && encoding.equalsIgnoreCase("deflate")) is = new InflaterInputStream(conn.getInputStream(), new Inflater(true)); else is = conn.getInputStream(); final InputStreamReader reader = new InputStreamReader(new BufferedInputStream(is)); final CharBuffer cb = CharBuffer.allocate(1024 * 1024); int ret; do { ret = reader.read(cb); } while (ret > 0); cb.flip(); return cb.toString(); }
From source file:info.icefilms.icestream.browse.Location.java
private static Bitmap DownloadImage(URL url, Callback callback) { try {// www . j av a 2s.co m // Open the connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0"); urlConnection.setConnectTimeout(callback.GetConnectionTimeout()); urlConnection.setReadTimeout(callback.GetConnectionTimeout()); urlConnection.connect(); // Get the input stream InputStream inputStream = urlConnection.getInputStream(); // For some reason we can actually get a null InputStream instead of an exception if (inputStream == null) { Log.e("Ice Stream", "Image download failed. Unable to create Input Stream."); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_image_download_error); } urlConnection.disconnect(); return null; } // Download the image and create the bitmap Bitmap bitmap = BitmapFactory.decodeStream(inputStream); // Close the connection inputStream.close(); urlConnection.disconnect(); // Check for errors if (bitmap == null) { Log.e("Ice Stream", "Image data decoding failed."); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_image_decode_error); } return null; } return bitmap; } catch (SocketTimeoutException exception) { Log.e("Ice Stream", "Image download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_image_timeout_error); } return null; } catch (IOException exception) { Log.e("Ice Stream", "Image download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_image_download_error); } return null; } }
From source file:net.ftb.util.DownloadUtils.java
/** * @param file - file on the repo in static * @return boolean representing if the file exists *//*w ww . j av a2 s. c o m*/ public static boolean staticFileExists(String file) { try { HttpURLConnection connection = (HttpURLConnection) new URL(getStaticCreeperhostLink(file)) .openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); connection.setRequestMethod("HEAD"); return (connection.getResponseCode() == 200); } catch (Exception e) { return false; } }
From source file:com.webarch.common.net.http.HttpService.java
/** * ?Http//from w w w .ja v a 2s . c o m * * @param requestUrl ? * @param requestMethod ? * @param outputJson ? * @return */ public static String doHttpRequest(String requestUrl, String requestMethod, String outputJson) { String result = null; try { StringBuffer buffer = new StringBuffer(); URL url = new URL(requestUrl); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); httpUrlConn.setUseCaches(false); httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET); httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET); // ?GET/POST httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // ???? if (null != outputJson) { OutputStream outputStream = httpUrlConn.getOutputStream(); //?? outputStream.write(outputJson.getBytes(DEFAULT_CHARSET)); outputStream.close(); } // ??? InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } result = buffer.toString(); bufferedReader.close(); inputStreamReader.close(); // ? inputStream.close(); httpUrlConn.disconnect(); } catch (ConnectException ce) { logger.error("server connection timed out.", ce); } catch (Exception e) { logger.error("http request error:", e); } finally { return result; } }