protected String getList(String method, String strUrl) { StringBuilder strJson = new StringBuilder(); try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) throw new RuntimeException("Failed : HTTP error code: " + conn.getResponseCode()); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String output; while ((output = br.readLine()) != null) { strJson.append(output); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return strJson.toString(); }
private static void readLatLong() { String buildingCode = "EEB"; StringBuilder query = new StringBuilder(""); query.append("PREFIX sgns: <http://www.smartgrid.usc.edu/Ontology/2012.owl#> \n"); query.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n"); query.append("PREFIX gmlns: <http://purl.org/ifgi/gml/0.1/> \n"); query.append("SELECT ?latitude ?longitude WHERE { \n"); query.append( " ?building <http://dbpedia.org/ontology/hasBuildingNo> '" + buildingCode + "' .\n"); query.append(" ?building gmlns:GeometryProperty ?gml . \n"); query.append(" ?gml sgns:hasLatitude ?latitude . \n"); query.append(" ?gml sgns:hasLongitude ?longitude . \n"); query.append(" } \n"); String sparql = query.toString(); System.out.println("\nSelectQuery: " + sparql); Store store = null; try { store = new Store(IIPProperties.getStoreURL()); String response = store.query(sparql, -1); System.out.println("Select response: " + response); } catch (MalformedURLException e) { e.getMessage(); e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override public InputStream doGetSound4Word(String ch) { Log.i(TAG, "get sound for word:" + ch + " from googel translate."); try { final URI uri = new URI("http://translate.google.cn/translate_tts?tl=zh-CN&q=" + ch); final URL u = new URL(uri.toASCIIString()); // this is the name of the local file you will create final HttpURLConnection connection = (HttpURLConnection) u.openConnection(); connection.addRequestProperty("User-Agent", "Mozilla/5.0"); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); final InputStream in = connection.getInputStream(); return in; } catch (URISyntaxException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
// прочитать весь json в строку private static String readAll() throws IOException { StringBuilder data = new StringBuilder(); try { HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("GET"); con.setDoInput(true); String s; try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { while ((s = in.readLine()) != null) { data.append(s); } } } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc."); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot read from server"); } return data.toString(); }
public void saveEmployer(String id, String firstName, String secondName, String deptId) throws JAXBException { URL servletUrl; try { servletUrl = new URL( Util.URL_SERVER + "/SaveEmployer?id=" + id + "&firstName=" + firstName + "&secondName=" + secondName + "&deptId=" + deptId); HttpURLConnection con = (HttpURLConnection) servletUrl.openConnection(); con.setDoInput(true); con.setRequestMethod("GET"); con.connect(); unmarshaller.unmarshal(new InputStreamReader(con.getInputStream())); ConnectionDBGUI.logger.log(Level.INFO, con.getResponseMessage()); con.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
protected Bitmap doInBackground(String... urls) { urlString = urls[0]; try { URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); } Log.v("connect", "Connecte to Internet"); int response = 0; try { connection.setRequestMethod("GET"); } catch (ProtocolException e) { e.printStackTrace(); } try { response = connection.getResponseCode(); } catch (IOException e) { e.printStackTrace(); } Log.v("RequestGet", "Request Method Get"); Log.v("Response", Integer.toString(response)); is = null; try { is = connection.getInputStream(); } catch (IOException e) { e.printStackTrace(); } bitmapImage = BitmapFactory.decodeStream(is); return bitmapImage; }
public String upload(String filepath) throws IOException { try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } connection.setDoOutput(true); connection.setReadTimeout(20000); connection.setConnectTimeout(20000); try { connection.setRequestMethod("POST"); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (connection == null) { return ""; } String filename = filepath; String fileSuffix = ""; int pos = filename.lastIndexOf("/"); filename = filename.substring(pos + 1); pos = filename.lastIndexOf("."); fileSuffix = filename.substring(pos + 1); File file = new File(filepath); FileInputStream fis = null; fis = new FileInputStream(file); long fileLength = file.length(); connection.setRequestProperty("Content-Type", getMIMEType(fileSuffix)); connection.setRequestProperty( "Content-Length", String.valueOf( fileLength + boundary.length() + (twoHyphens.length() + lineEnd.length()) * 2)); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Disposition", "attachment;filename=" + filename); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); byte[] inputBuffer = new byte[1024]; int len = 0; long totalSentLength = 0; while ((len = fis.read(inputBuffer, 0, 1024)) > 0) { outputStream.write(inputBuffer, 0, len); totalSentLength += len; System.out.println("File uploaded:" + (float) totalSentLength / (float) fileLength); if (listener != null) { listener.onUpload((float) totalSentLength / (float) fileLength); } } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); outputStream.flush(); BufferedReader outputBuffer = new BufferedReader(new InputStreamReader(connection.getInputStream())); String returnString = outputBuffer.readLine(); return returnString; }
@JavascriptInterface public String approveNewVolunteersInit() { HttpURLConnection connection = null; OutputStreamWriter wr = null; BufferedReader rd = null; StringBuilder sb = null; String line = null; String ret; URL serverAddress = null; try { serverAddress = new URL( "http://env-3010859.jelastic.servint.net/Controller/approveNewVolunteersInit.jsp"); // Set up the initial connection connection = (HttpURLConnection) serverAddress.openConnection(); connection.setRequestMethod("GET"); // connection.setDoOutput(true); connection.setReadTimeout(10000); // connection = (HttpURLConnection) serverAddress.openConnection(); // get the output stream writer and write the output to the server // not needed in this example /* wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(""); wr.flush(); */ // read the result from the server rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } ret = sb.toString(); } catch (MalformedURLException e) { e.printStackTrace(); ret = "false1"; } catch (ProtocolException e) { e.printStackTrace(); ret = "false2"; } catch (IOException e) { e.printStackTrace(); ret = "false3"; } finally { // close the connection, set all objects to null connection.disconnect(); rd = null; sb = null; wr = null; connection = null; } return (ret); }
@Override protected String doInBackground(String... params) { publishProgress("Verifying..."); // Calls onProgressUpdate() String pin = params[0]; // creating a json file to be posted JSONObject obj = new JSONObject(); try { obj.put("pin", pin); // JSONArray ja=new JSONArray(); // ja.put(obj); // JSONObject rootObj = new JSONObject(); // rootObj.put("login",ja); // String json=rootObj.toString(); String json = obj.toString(); String url = "http://41.74.172.132:8080/PetroStationManager/androiddata/login"; // _____________Opening connection and post data____________// URL oURL = new URL(url); HttpURLConnection con = (HttpURLConnection) oURL.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "Application/json; charset=UTF-8"); con.setDoOutput(true); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(json); wr.flush(); wr.close(); System.out.println("Data to post :" + json); BufferedReader in1 = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in1.readLine()) != null) { response.append(inputLine); } in1.close(); con.disconnect(); return response.toString(); } catch (JSONException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
public String upload(byte[] data, String filePath) throws IOException { try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } connection.setDoOutput(true); connection.setReadTimeout(20000); connection.setConnectTimeout(20000); try { connection.setRequestMethod("POST"); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (connection == null) { return ""; } String fileName = this.getFileName(filePath); String fileSuffix = this.getSuffix(filePath); connection.setRequestProperty("Content-Type", this.getMIMEType(fileSuffix)); connection.setRequestProperty( "Content-Length", String.valueOf( data.length + boundary.length() + (twoHyphens.length() + lineEnd.length()) * 2)); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Disposition", "attachment;filename=" + fileName); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); int len = 0; int totalSentLength = 0; while (totalSentLength < data.length) { if (data.length - totalSentLength > 1024) { len = 1024; } else { len = data.length - totalSentLength; } outputStream.write(data, totalSentLength, len); totalSentLength += len; if (listener != null) { listener.onUpload((float) totalSentLength / (float) data.length); } } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); outputStream.flush(); BufferedReader outputBuffer = new BufferedReader(new InputStreamReader(connection.getInputStream())); String returnString = outputBuffer.readLine(); return returnString; }
/** * Connects to the resource on the supplied server at the requested path. Ensures that the * response is HTTP 200 and then prints the contents to the screen. */ public void run() { int retry = 0; while (retry <= 1) { retry++; BufferedReader br = null; HttpURLConnection conn = null; try { URL url = new URL(server + path); conn = (HttpURLConnection) url.openConnection(); conn.setInstanceFollowRedirects(false); conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } } else if (responseCode == 302) { continue; } else { System.out.println(conn.getResponseMessage()); } } catch (ProtocolException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException ex) { } } if (conn != null) { try { conn.disconnect(); } catch (Exception ex) { } } } break; } }
// добавить продукт в базу json server public static void add(ProductREST product) throws NotValidProductException, IOException { try { check(product); // рповеряем продукт // connection к серверу HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("POST"); // метод post для добавления // генерируем запрос StringBuilder urlParameters = new StringBuilder(); urlParameters .append("name=") .append(URLEncoder.encode(product.getName(), "UTF8")) .append("&"); urlParameters.append("price=").append(product.getPrice()).append("&"); urlParameters.append("weight=").append(product.getWeight()).append("&"); urlParameters .append("manufacturer=") .append(product.getManufacturer().getCountry()) .append("&"); urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8")); con.setDoOutput(true); // разрешаем отправку данных // отправляем try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) { out.writeBytes(urlParameters.toString()); } // код ответа int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL); System.out.println("Response Code : " + responseCode); } catch (NotValidProductException e) { e.printStackTrace(); throw e; } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new UnsupportedEncodingException("cannot recognize encoding"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc."); } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot write information to server"); } }
public static String get(String url) { int c = 0; while (c < 5) { try { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); // int responseCode = con.getResponseCode(); // System.out.println("\nSending 'GET' request to URL : " + url); // System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result // System.out.println(response.toString()); return response.toString(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { System.out.println("Cought Exception"); if (e instanceof ConnectException) { c++; System.out.println("Cought ConnectException: " + c); } } } return null; }
@Override protected Void doInBackground(String... params) { URL url = null; try { url = new URL(params[0]); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); } try { httpURLConnection.setRequestMethod("GET"); } catch (ProtocolException e) { e.printStackTrace(); } InputStream inputStream = null; try { inputStream = httpURLConnection.getInputStream(); } catch (IOException e) { e.printStackTrace(); } StringBuffer jsonBuffer = new StringBuffer(); if (inputStream == null) { return null; } Scanner s = new Scanner(inputStream); while (s.hasNext()) { jsonBuffer.append(s.nextLine()); } Log.i("pppppp", jsonBuffer.toString()); return null; }
public EmployerList getEmployers() throws JAXBException { EmployerList employerList = null; URL servletUrl; try { servletUrl = new URL(Util.URL_SERVER + "/GetEmployers"); HttpURLConnection con = (HttpURLConnection) servletUrl.openConnection(); con.setDoInput(true); con.setRequestMethod("GET"); con.connect(); employerList = (EmployerList) unmarshaller.unmarshal(new InputStreamReader(con.getInputStream())); con.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return employerList; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); InputStream is = null; URL url = null; try { url = new URL("https://www.google.es/images/srpr/logo11w.png"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /*milisegons*/); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); /*recibimos datos*/ // empieza la conexion conn.connect(); int response = conn.getResponseCode(); is = conn.getInputStream(); // conversion del inputStream Bitmap bitmap = BitmapFactory.decodeStream(is); ImageView imageView = (ImageView) findViewById(R.id.image_view); imageView.setImageBitmap(bitmap); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } }
/** * 通过IP获取地址 * * @param ip * @return */ public static String getIpInfo(String ip) { String info = ""; try { URL url = new URL("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip); HttpURLConnection htpcon = (HttpURLConnection) url.openConnection(); htpcon.setRequestMethod("GET"); htpcon.setDoOutput(true); htpcon.setDoInput(true); htpcon.setUseCaches(false); InputStream in = htpcon.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in)); StringBuffer temp = new StringBuffer(); String line = bufferedReader.readLine(); while (line != null) { temp.append(line).append("\r\n"); line = bufferedReader.readLine(); } bufferedReader.close(); JSONObject obj = (JSONObject) JSON.parse(temp.toString()); if (obj.getIntValue("code") == 0) { JSONObject data = obj.getJSONObject("data"); info += data.getString("country") + " "; info += data.getString("region") + " "; info += data.getString("city") + " "; info += data.getString("isp"); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return info; }
public static Item getItemById(String id) { URL url; String json = ""; try { // send call to api url = new URL(API_URL + "/" + id); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); InputStream stream = conn.getInputStream(); json = convertStreamToString(stream); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ItemBuilder.build(json); }
@Override protected Boolean doInBackground(URL... urls) { InputStream is = null; boolean toret = false; ConnectivityManager connMgr = (ConnectivityManager) this.activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); boolean connected = (networkInfo != null && networkInfo.isConnected()); if (!connected) { this.activity.setTimeInfo("No internet"); } else { HttpURLConnection conn = null; try { conn = (HttpURLConnection) urls[0].openConnection(); } catch (IOException e) { e.printStackTrace(); } conn.setReadTimeout(1000 /* milliseconds */); conn.setConnectTimeout(1000 /* milliseconds */); try { conn.setRequestMethod("GET"); } catch (ProtocolException e) { e.printStackTrace(); } conn.setDoInput(true); try { conn.connect(); } catch (IOException e) { e.printStackTrace(); } try { is = conn.getInputStream(); } catch (IOException e) { e.printStackTrace(); } JSONObject json = null; try { json = new JSONObject(getStringFromStream(is)); } catch (JSONException e) { e.printStackTrace(); } try { if (json != null) { this.time = json.getString("time"); } } catch (JSONException e) { e.printStackTrace(); } toret = true; } return toret; }
public static String httpPost(String urlAddress, String[] params) { URL url = null; HttpURLConnection conn = null; BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { url = new URL(urlAddress); conn = (HttpURLConnection) url.openConnection(); // 建立连接 // 设置通用的请求属性 /* * conn.setRequestProperty("user-agent", * "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); */ conn.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setUseCaches(false); conn.setDoInput(true); // conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true); conn.setRequestMethod("POST"); String paramsTemp = ""; for (String param : params) { if (param != null && !"".equals(param)) { if (params.length > 1) { paramsTemp += "&" + param; } else if (params.length == 1) { paramsTemp = params[0]; } } } byte[] b = paramsTemp.getBytes(); System.out.println("btye length:" + b.length); // conn.setRequestProperty("Content-Length", // String.valueOf(b.length)); conn.getOutputStream().write(b, 0, b.length); conn.getOutputStream().flush(); conn.getOutputStream().close(); int count = conn.getResponseCode(); if (200 == count) { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // 发送请求 } else { System.out.println("错误类型:" + count); return "server no start-up"; } while (true) { String line = in.readLine(); if (line == null) { break; } else { sb.append(line); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { System.out.println("error ioexception:" + e.getMessage()); e.printStackTrace(); return "server no start-up"; } finally { try { if (in != null) { in.close(); } if (conn != null) { conn.disconnect(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return sb.toString(); }
@SuppressWarnings("unchecked") // HashMap<...,...> @Override protected Object doInBackground( Object... params) { // url, useCache, headers (auth,content-type), method, callback Log.d(TAG, "doInBackground"); // default params int connectTimeout = 10000; // 10 seconds int readTimeout = 15000; // 15 seconds HashMap<String, Object> inParams; String requestMethod = "GET"; int requestExpectedType = TYPE_EXPECTED_JSON; String requestURL = "http://www.reddit.com/.json"; HashMap<String, String> requestProperties = null; // new HashMap<String,String>(); Boolean requestCaching = true; Callback requestCallback = null; // get input params if (params.length == 1) { Object paramZero = params[0]; if (paramZero instanceof Callback) { requestCallback = (Callback) paramZero; } else if (paramZero instanceof HashMap) { inParams = (HashMap<String, Object>) paramZero; if (inParams.get(PARAM_CALLBACK) != null) { requestCallback = (Callback) inParams.get(PARAM_CALLBACK); } if (inParams.get(PARAM_URL) != null) { requestURL = (String) inParams.get(PARAM_URL); } if (inParams.get(PARAM_METHOD) != null) { requestMethod = (String) inParams.get(PARAM_METHOD); } if (inParams.get(PARAM_CACHE) != null) { requestCaching = (Boolean) inParams.get(PARAM_CACHE); } if (inParams.get(PARAM_PROPERTIES) != null) { HashMap<String, String> props = (HashMap<String, String>) inParams.get(PARAM_PROPERTIES); requestProperties = props; } if (inParams.get(PARAM_EXPECTED) != null) { requestExpectedType = (Integer) inParams.get(PARAM_EXPECTED); } } } // set callback callback = new WeakReference<Callback>(requestCallback); // set url URL url; try { url = new URL(requestURL); } catch (MalformedURLException e) { e.printStackTrace(); return null; } // set connection try { connection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); return null; } // set cache connection.setUseCaches(requestCaching); // set properties if (requestProperties != null) { for (Entry<String, String> entry : requestProperties.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } // set timeouts connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(readTimeout); // set method try { connection.setRequestMethod(requestMethod); } catch (ProtocolException e) { e.printStackTrace(); } // get response code try { responseCode = connection.getResponseCode(); } catch (IOException e) { e.printStackTrace(); } // get response try { responseObject = connection.getContent(); } catch (IOException e) { e.printStackTrace(); return null; } // return data if (this.isCancelled()) { return null; } Object object = Networking.connectionResultToKnownType(connection, requestExpectedType); try { // check that stream is closed before returning InputStream inStream = connection.getInputStream(); inStream.close(); } catch (IOException e) { e.printStackTrace(); } return object; }
private void test() { HttpURLConnection fbc; String response = ""; boolean isConnectionError = false; String connectionErrorMessage = ""; String uidstr = Long.toString(uid); boolean unknown = true; long random = new Random().nextInt(); long channel = 65; long seq = 0; String endpoint = createEndpoint(channel, random, unknown, uidstr, seq); String endpointHost = createEndpointHost(channel, random, unknown, uidstr, seq); String endpointFile = createEndpointFile(channel, random, unknown, uidstr, seq); // endpoint = "http://www.google.com"; int mConnectionTimeout = 50000; String REQUEST_METHOD = "GET"; response = ""; CookieManager cm = CookieManager.getInstance(); String cookies = cm.getCookie("facebook.com"); Log.d(LOG_TAG, "cookie: " + cookies); try { HttpClientConnection httpClientConn; URL url = new URL("http", endpointHost, 80, endpointFile); Log.d(LOG_TAG, "url to connect:" + url.toString()); fbc = (HttpURLConnection) url.openConnection(); fbc.setUseCaches(true); fbc.setConnectTimeout(mConnectionTimeout); fbc.setRequestMethod(REQUEST_METHOD); fbc.setRequestProperty("Content-type", REQUEST_CONTENT_TYPE); fbc.setRequestProperty("User-Agent", REQUEST_USER_AGENT); fbc.setRequestProperty("Accept-Language", REQUEST_ACCEPT_LANGUAGE); fbc.setRequestProperty("Accept", REQUEST_ACCEPT); fbc.setRequestProperty("Accept-Charset", REQUEST_ACCEPT_CHARSET); fbc.setRequestProperty("Cookie", cookies); // DataOutputStream dos = new DataOutputStream(fbc.getOutputStream()); // dos.writeBytes(response); // dos.flush(); // dos.close(); // fbc.connect(); // fbc.getContent(); /* try{ Object obj = fbc.getContent(); Log.d(LOG_TAG,"content class: " + obj.getClass().getCanonicalName()); } catch(Exception e){ } */ // String responseMsg = fbc.getResponseMessage(); // Log.d(LOG_TAG,"response message:"+responseMsg); InputStream is = fbc.getInputStream(); BufferedReader breader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); int linecount = 0; while (true) { String line = breader.readLine(); if (line == null) { break; } linecount++; response += line; Log.d(LOG_TAG, linecount + ":" + line); } Log.d(LOG_TAG, "TEST_DONE"); } catch (MalformedURLException e) { e.printStackTrace(); isConnectionError = true; connectionErrorMessage = "MalformedURLException: " + e.getMessage(); } catch (ProtocolException e) { e.printStackTrace(); isConnectionError = true; connectionErrorMessage = "ProtocolException: " + e.getMessage(); } catch (UnknownHostException e) { e.printStackTrace(); isConnectionError = true; connectionErrorMessage = "UnknownHostException: " + e.getMessage(); } catch (IOException e) { e.printStackTrace(); isConnectionError = true; connectionErrorMessage = "IOException: " + e.getMessage(); } }
@JavascriptInterface public String signUp( String firstName, String lastName, String userName, String pass, String id, String phoneNumber, String email) { HttpURLConnection connection = null; OutputStreamWriter wr = null; BufferedReader rd = null; StringBuilder sb = null; String line = null; String ret; URL serverAddress = null; try { serverAddress = new URL("http://env-3010859.jelastic.servint.net/Controller/signUp.jsp"); // Set up the initial connection connection = (HttpURLConnection) serverAddress.openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(10000); connection.setRequestProperty("firstName", firstName); connection.setRequestProperty("lastName", lastName); connection.setRequestProperty("userName", userName); connection.setRequestProperty("password", pass); connection.setRequestProperty("id", id); connection.setRequestProperty("phoneNumber", phoneNumber); connection.setRequestProperty("email", email); // get the output stream writer and write the output to the server // not needed in this example /* * wr = new OutputStreamWriter(connection.getOutputStream()); * wr.write(""); wr.flush(); */ // read the result from the server rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); sb = new StringBuilder(); while ((line = rd.readLine()) != null) { sb.append(line); } ret = sb.toString(); } catch (MalformedURLException e) { e.printStackTrace(); ret = "false1"; } catch (ProtocolException e) { e.printStackTrace(); ret = "false2"; } catch (IOException e) { e.printStackTrace(); ret = "false3"; } finally { // close the connection, set all objects to null connection.disconnect(); rd = null; sb = null; wr = null; connection = null; } return (ret); }
/** * Talks to the OpenAM server * * @param readProgress Thread that prints out the current progress of the installation * @param openAmURL URL of the OpenAM instance to update * @return true if installation succeeds, false otherwise */ private boolean postRequestToServer(Thread readProgress, String openAmURL) { DataOutputStream os = null; BufferedReader br = null; HttpURLConnection conn = null; try { URL url = new URL(openAmURL + "/config/configurator"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Length", Integer.toString(postBodySB.length())); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.connect(); os = new DataOutputStream(conn.getOutputStream()); os.writeBytes(postBodySB.toString()); os.flush(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String str; while ((str = br.readLine()) != null) { System.out.println(str); } } else { System.out.println(rb.getString("configFailed")); if ((userStoreType != null) && (userStoreType.equals("LDAPv3ForADDC"))) { System.out.println(rb.getString("cannot.connect.to.UM.datastore")); } return false; } } catch (ProtocolException ex) { ex.printStackTrace(); return false; } catch (IOException ex) { ex.printStackTrace(); return false; } finally { if (os != null) { try { os.close(); } catch (IOException ex) { } } if (br != null) { try { br.close(); } catch (IOException ex) { } } try { // wait 5 seconds if ReadProgress thread does not finished. readProgress.join(5000); } catch (InterruptedException e) { } if (conn != null) { try { conn.disconnect(); } catch (Exception ex) { } } } return true; }
@Override public void run() { try { String end = "\r\n"; String twoHyphens = "--"; String boundary = "*****++++++************++++++++++++"; URL url = new URL(ApplicationConfig.UploadMessageAttachments); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(2000); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); dataOutputStream.writeBytes(twoHyphens + boundary + end); dataOutputStream.writeBytes( "Content-Disposition: form-data; name=\"txtFrom\"" + end + end + chatContent.get(0) + end); dataOutputStream.writeBytes(twoHyphens + boundary + end); dataOutputStream.writeBytes( "Content-Disposition: form-data; name=\"txtTo\"" + end + end + chatContent.get(1) + end); dataOutputStream.writeBytes(twoHyphens + boundary + end); dataOutputStream.writeBytes( "Content-Disposition: form-data; name=\"txtType\"" + end + end + chatContent.get(2) + end); dataOutputStream.writeBytes(twoHyphens + boundary + end); dataOutputStream.writeBytes( "Content-Disposition: form-data; name=\"txtTile\"" + end + end + URLEncoder.encode(chatContent.get(3), "UTF-8") + end); dataOutputStream.writeBytes(twoHyphens + boundary + end); dataOutputStream.writeBytes( "Content-Disposition: form-data; name=\"extension\"" + end + end + chatContent.get(4) + end); dataOutputStream.writeBytes(twoHyphens + boundary + end); dataOutputStream.writeBytes( "Content-Disposition: form-data; name=\"FileUpload1\";filename=\"" + URLEncoder.encode(chatContent.get(5), "UTF-8") + "\"" + end); dataOutputStream.writeBytes(end); int totalLength = uploadInputStream.available(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int uploaded = 0; int length = -1; while ((length = uploadInputStream.read(buffer)) != -1) { if (isCanceled) { dataOutputStream.flush(); dataOutputStream.close(); break; } dataOutputStream.write(buffer, 0, length); uploaded += length; Message message = new Message(); message.what = UpdateProgressMessage; int percent = (uploaded * 100) / totalLength; // Wait server process file if (percent == 100) { percent = 99; } message.obj = percent; transportHandler.sendMessage(message); } if (!isCanceled) { dataOutputStream.writeBytes(end); dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + end); uploadInputStream.close(); dataOutputStream.flush(); dataOutputStream.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { Message message = new Message(); message.what = UpdateProgressMessage; message.obj = 100; transportHandler.sendMessage(message); if (mUploadListener != null) { String fileName = chatContent.get(0) + "-" + chatContent.get(1) + "-" + chatContent.get(2) + "-" + chatContent.get(3) + "." + chatContent.get(4); mUploadListener.onUploadComplete(fileName); } transportHandler.sendEmptyMessage(TransportComplete); } else { transportHandler.sendEmptyMessage(TransportFailed); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (SocketTimeoutException e) { transportHandler.sendEmptyMessage(ConnectTimeOut); } catch (ProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@Override // Cette méthode s'execute en deuxième protected String doInBackground(String... params) { ConnectivityManager check = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo[] info = check.getAllNetworkInfo(); for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { String result; try { /////////////////////////////// REQUETE HTTP ///////////////////// URL url = new URL( "http://humanapp.assos.efrei.fr/shareyoursport/script/shareyoursportcontroller.php"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(3000); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); /// Mise en place des differents parametre necessaire //// Uri.Builder builder = new Uri.Builder().appendQueryParameter("OBJET", "total"); String query = builder.build().getEncodedQuery(); OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.flush(); writer.close(); os.close(); connection.connect(); /////////////////////////////// BUFFERREADER///////////////////// Reader reader = new InputStreamReader(connection.getInputStream(), "UTF-8"); char[] buffer = new char[50]; System.out.println("\n\n\n\n\n\n\n\n\n\n\n CHAAAAR : " + buffer + "\n\n\n\n\n "); reader.read(buffer); // / On recupere ce que nous a envoyés le fichier php result = new String(buffer); reader.close(); ////////////////////// JSON//////////////////////////////////// try { System.out.println("\n\n\n\n\n\n\n\n\n\n\n TEEESSSSTTTT \n\n\n\n\n "); JSONObject object = new JSONObject(result); System.out.println( "\n\n\n\n\n\n\n\n\n\n\n TEEESSSSTTTT 2222222 : " + object.getString("total") + "\n\n\n\n\n "); connection.disconnect(); return object.getString("total"); // On retourne true ou false } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
@Override protected Void doInBackground(Void... params) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(RegistrationIntentService.this); URL url = null; try { url = new URL(Config.WEB_SERVER_URL); } catch (MalformedURLException e) { e.printStackTrace(); sharedPreferences.edit().putString(Config.PREF_GCM_REG_ID, "").apply(); } Map<String, String> dataMap = new HashMap<String, String>(); dataMap.put("regID", GMC2Activity.newRegID); StringBuilder postBody = new StringBuilder(); Iterator<Map.Entry<String, String>> iterator = dataMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = (Entry<String, String>) iterator.next(); postBody.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { postBody.append('&'); } } String body = postBody.toString(); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); String response = ""; InputStream is = null; try { is = conn.getInputStream(); int ch; StringBuffer sb = new StringBuffer(); while ((ch = is.read()) != -1) { sb.append((char) ch); } response = sb.toString(); } catch (IOException e) { throw e; } finally { if (is != null) { is.close(); } } int status = conn.getResponseCode(); if (status == 200) { if (response.equals("1")) { sharedPreferences .edit() .putString(Config.PREF_GCM_REG_ID, GMC2Activity.newRegID) .apply(); Intent registrationComplete = new Intent(Config.SERVER_SUCCESS); LocalBroadcastManager.getInstance(RegistrationIntentService.this) .sendBroadcast(registrationComplete); } } else { throw new IOException("Request failed with error code " + status); } } catch (ProtocolException pe) { pe.printStackTrace(); sharedPreferences.edit().putString(Config.PREF_GCM_REG_ID, "").apply(); } catch (IOException io) { io.printStackTrace(); sharedPreferences.edit().putString(Config.PREF_GCM_REG_ID, "").apply(); } finally { if (conn != null) { conn.disconnect(); } } return null; }