Android 常用代码---WEB
来源:互联网 发布:张怡宁 知乎 编辑:程序博客网 时间:2024/06/15 22:25
1执行 GET 请求权限<uses-permission android:name="android.permission.INTERNET"/>代码URI myURI = null;try { myURI = new URI("www.webserver.org");} catch (URISyntaxException e) { // Deal with it}HttpClient httpClient = new DefaultHttpClient();HttpGet getMethod = new HttpGet(myURI);HttpResponse webServerResponse = null;try { webServerResponse = httpClient.execute(getMethod);} catch (ClientProtocolException e) { // Deal with it} catch (IOException e) { // Deal with it}HttpEntity httpEntity = webServerResponse.getEntity();if (httpEntity != null) { // You have your response, handle it. For instance, with a input // stream // InputStream input = entity.getContent();}2执行 POST 请求权限<uses-permission android:name="android.permission.INTERNET"/>代码// Create the Apache HTTP client and post HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.website.org/service.php"); try { // Add data to your post List<NameValuePair> pairs = new ArrayList<NameValuePair>(2); pairs.add(new BasicNameValuePair("ID", "VALUE")); pairs.add(new BasicNameValuePair("string", "Yeah!")); httppost.setEntity(new UrlEncodedFormEntity(pairs)); //Finally, execute the request HttpResponse webServerAnswer = httpclient.execute(httppost); } catch (ClientProtocolException e) { //Deal with it } catch (IOException e) { //Deal with it }3从服务器响应检索 JSON 权限<uses-permission android:name="android.permission.INTERNET"/>代码// The JSON objectsJSONObject myJSON = null;JSONArray names = null;JSONArray values = null;String restWebServerResponse = "TheResponse";try{ myJSON = new JSONObject(restWebServerResponse); names = myJSON.names(); values = myJSON.toJSONArray(names); }catch (JSONException e) { // Deal with it} for (int i = 0; i < values.length(); i++) { // Do something with the values.getString(i)}4使用 GET 请求查询 Web 服务器中的 REST 响应权限<uses-permission android:name="android.permission.INTERNET"/>代码// This assumes that you have a URL from which to get the answerURI myURL = new URI("www.website.org");// The HTTP objectsHttpClient httpClient = new DefaultHttpClient();HttpGet getMethod = new HttpGet(myURL);HttpResponse httpResponse;// The query resultString result = null;try { httpResponse = httpClient.execute(getMethod); // You might want to check response.getStatusLine().toString() HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); BufferedReader reader = new BufferedReader( new InputStreamReader(instream)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { // Deal with it } finally { try { instream.close(); } catch (IOException e) { // Deal with it } } // Handle the result (for instance, get a JSON object // using the "Retrieve JSON from a server response" snippet) handleResult(result); }} catch (ClientProtocolException e) { // Deal with it} catch (IOException e) { // Deal with it}5发送电子邮件权限<uses-permission android:name="android.permission.INTERNET"/>代码Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);emailIntent.setType("plain/text"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"to@email.com"});emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hello, MOTO!"); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hello, MOTO!"); startActivity(Intent.createChooser(emailIntent, "Send mail..."));6从 URL 检索日期权限<uses-permission android:name="android.permission.INTERNET"/>代码// The data that is retrieved String result = null;try { // This assumes that you have a URL from which the response will come URL url = new URL("www.webaddress.org"); // Open a connection to the URL and obtain a buffered input stream URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); BufferedInputStream bufferedInput = new BufferedInputStream(inputStream); // Read the response into a byte array ByteArrayBuffer byteArray = new ByteArrayBuffer(50); int current = 0; while((current = bufferedInput.read()) != -1){ byteArray.append((byte)current); } // Construct a String object from the byte array containing the response result = new String(byteArray.toByteArray());} catch (Exception e) {}// Handle the resulthandleResult(result);7SOAP 示例权限<uses-permission android:name="android.permission.INTERNET"/>代码/* This example is intended to be used with the KSoap * project (http://ksoap2.sourceforge.net/), which * provides some objects to deal with SOAP within * mobile development. * * You must download the KSoap objects and * have something like this in your import list: * import org.ksoap2.SoapEnvelope; // (and other necessary classes) */String SOAP_ACTION = "yourMethod";String METHOD_NAME = "yourMethod";String NAMESPACE = "http://namespace.com/";String URL = "http://server.org";SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);request.addProperty("property1", "property");SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);envelope.setOutputSoapObject(request);HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);androidHttpTransport.call(SOAP_ACTION, envelope);Object results = envelope.getResponse();// Handle the resultshandleResults(results);