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(); }
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 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(); } }
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(); } }
// прочитать весь 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(); }
private InputStream processGetRequest(URL url, String keyStore, String keyStorePassword) { SSLSocketFactory sslFactory = getSSLSocketFactory(keyStore, keyStorePassword); HttpsURLConnection con = null; try { con = (HttpsURLConnection) url.openConnection(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } con.setSSLSocketFactory(sslFactory); try { con.setRequestMethod(REQUEST_METHOD_GET); } catch (ProtocolException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } con.addRequestProperty(X_MS_VERSION_HEADER, X_MS_VERSION); InputStream responseStream = null; try { responseStream = (InputStream) con.getContent(); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } return responseStream; }
@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; }
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; }
static void setRequestMethod(HttpURLConnection urlConnection, String method) { try { urlConnection.setRequestMethod(method); if (method.equalsIgnoreCase(POST_METHOD) || method.equalsIgnoreCase(PUT_METHOD)) { urlConnection.setDoOutput(true); } } catch (ProtocolException e) { Log.e("URLConnection exception", e.toString()); } }
/** * 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; }
private void prepareRequest(String method) throws IOException, FisherException { try { conn = (HttpURLConnection) uri.openConnection(); // Set method: GET, POST,... conn.setRequestMethod(method); // Set Headers if (headers != null) { for (String key : headers.fields.keySet()) { conn.setRequestProperty(key, headers.getField(key, null).asString(null)); } } } catch (ProtocolException e) { System.err.println("ProtocolException: " + e.getMessage()); } }
public void run() { String fileName; ResponseCallback cb = new ResponseCallback(mComm, mEvent); try { if ((fileName = Serialization.DecodeString(mEvent.payload)) == null) throw new ProtocolException("Filename not properly encoded in request packet"); mBroker.Remove(cb, fileName); } catch (ProtocolException e) { int error = cb.error(Error.PROTOCOL_ERROR, e.getMessage()); log.severe("Protocol error (REMOVE) - " + e.getMessage()); if (error != Error.OK) log.severe("Problem sending (REMOVE) error back to client - " + Error.GetText(error)); } }
@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 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(); } }
private void transfer(HttpsURLConnection conn, String filename) { DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; try { conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setUseCaches(false); // Don't use a Cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes( "Content-Disposition: form-data; name=\"" + filename + "\";filename=\"" + filename + "\"" + lineEnd); dos.writeBytes(lineEnd); FileInputStream fileInputStream = this.context.openFileInput(filename); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); Log.v("mark", "reading " + bytesRead + " bytes"); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.v("mark", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); fileInputStream.close(); DataInputStream dis = new DataInputStream(conn.getInputStream()); if (dis.available() > 0) { byte[] buf = new byte[256]; dis.read(buf); Log.v("mark", "line1:" + new String(buf)); } else { Log.v("mark", "line1:none"); } // close the streams // // if(dis.available()>0){ // byte[] buf = new byte[256]; // dis.read(buf); // Log.v("mark","line2:"+new String(buf)); // }else{ // Log.v("mark","line2:none"); // } dis.close(); dos.flush(); dos.close(); } catch (ProtocolException e) { Log.v("mark", "ProtocolException:" + e.getMessage()); } catch (IOException e) { Log.v("mark", "IOException:" + e.getMessage()); } }
@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; }
/** * 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; }
@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(); } }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = ""; boolean success = false; String baseUrl = request.getParameter(PARAM_SEED_HUB); String accessKey = request.getParameter(AppConstants.SETTINGS_ACCESS_KEY); // Non empty parameters if (baseUrl == null || accessKey == null) { baseUrl = ""; accessKey = ""; } if (baseUrl.equals("") || accessKey.equals("")) { throw new ServletException("accessKey and baseUrl must be defined."); } // Access key should have no value on database. Or if it's present it must coincide with the // given value try { String dbKey = SettingsBusiness.getAccessKey(); if (dbKey != null) { if (!dbKey.equals(accessKey)) { throw new ServletException( "accessKey already exists. This software has already been installed."); } } } catch (OrmException e) { throw new ServletException(e.getMessage(), e); } // Set accessKey try { SettingsBusiness.setAccessKey(accessKey); } catch (OrmException e) { throw new ServletException(e.getMessage(), e); } message += "Access key has been correctly set.<br/><br/>"; // Hub list should be empty boolean emptyHubList = true; try { List<Hubs> hubList = HubBusiness.findAllHubs(true, false); if (hubList != null) { if (hubList.size() > 0) { message += "The first hub has already been defined."; emptyHubList = false; } } } catch (OrmException e) { throw new ServletException(e.getMessage(), e); } // Set the seed Hubs hub = null; if (emptyHubList) { // Look for hub baseUrl String pollUrl = null; try { if (baseUrl != null) { String baseUrlParam = HubBusiness.cleanBaseUrl(baseUrl); pollUrl = baseUrlParam + AppConstants.JSON_SITEINFO; if (urlExists(pollUrl)) { baseUrl = baseUrlParam; } } LOG.debug("baseUrl = " + baseUrl); LOG.debug("response from pollUrl = " + pollUrl); if (baseUrl != null) { try { // Revive or add hub hub = HubBusiness.addHub(baseUrl); message += "Your hub have been correctly registered.<br />" + "It will be included in global statistics within 24 hours."; success = true; } catch (Exception e) { // UrlException, BusinessException and OrmException => exit with error message LogBusiness.addLog(AppConstants.LOG_DEBUG, "install", e.getMessage()); message = baseUrl + " could not be added.<br />" + "Cause: " + e.getMessage(); LOG.error(message, e); } } else { message = "The hub base URL is incorrect. Please re-submit this page."; } } catch (ProtocolException e) { message = e.getMessage(); LOG.debug(e.getMessage(), e); } catch (IOException e) { message = e.getMessage(); LOG.debug(e.getMessage(), e); } } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" + "<html> \n" + "<head> \n" + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"> \n" + "<title>Hubzilla hub registration</title> \n" + "<meta name='viewport' content='width=device-width, initial-scale=1'>" + "<link href='css/bootstrap.min.css' rel='stylesheet'>" + "</head> \n" + "<body> \n" + "<div class='container'>" + "<h1><img src='images/hubchart2-32.png' align='middle' /> hubchart</h1>" + " <br />"); if (success) { out.println("<p>" + message + "</p>"); if (hub != null) { out.println("<p>"); out.println("Name: " + hub.getName() + "<br />"); out.println("Base URL: " + hub.getBaseUrl() + "<br />"); String icon = AppConstants.NETWORK_ICONS.get(hub.getNetworkType()); if (icon == null) icon = AppConstants.NETWORK_ICON_UNKNOWN; out.println( "Network: <img src='" + icon + "' border='0'/> " + hub.getNetworkType() + "<br />"); // out.println("Server location: <img // src='"+LookupUtil.decodeCountryToFlag(hub.getCountryCode())+"' /> "+ // hub.getCountryName()+"<br />"); out.println( "Registration: " + AppConstants.REGISTRATION_DESCRIPTIONS.get(hub.getRegistrationPolicy()) + "<br />"); out.println("Version: " + hub.getVersion() + "<br />"); out.println("</p>"); } } else { out.println("<p style='color:#c60032;'>ERROR: " + message + "</p>"); out.println( "<p>You must provide a correct and working base URL in the form <br />" + "<code>https://<domain></code><br />" + "<code>http://<domain></code><br />" + "<code>http(s)://<domain>/<base_dir></code><br /><br />" + "Please check the <b>http</b> or <b>https</b> prefix!<br /><br />" + "If you find a bug please contact the author</a>.<br /><br />"); } out.println("<a href='index.jsp'><b><- back</b></a>"); out.println("</div><!-- /container -->"); out.println("</body> \n" + "</html>"); }
@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); }