Android 常用代码---WEB

本文介绍了如何使用Android进行GET和POST网络请求,并展示了如何解析服务器返回的JSON数据,还涉及了从URL获取数据、发送邮件等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 objects
JSONObject 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 answer
URI myURL = new URI("www.website.org");
// The HTTP objects
HttpClient httpClient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet(myURL);
HttpResponse httpResponse;
// The query result
String 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 result
handleResult(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 results
handleResults(results);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值