Android data storage network storage data

 The several types of storage described above all store data on local devices. In addition, there is another way to store (obtain) data, which can be used to store and obtain data through the network.

 

We can call the data returned by WebService or parse the HTTP protocol to realize network data interaction.

 

Specifically, you need to be familiar with the contents of the two packages, java.net.* and Android.net.*. I won’t go into details here. Please refer to the relevant documents.

 

 

 

The following is a query for the weather forecast of the region through the name of the region, send a request to the webservicex.net site by POST, and access the service provided on the WebService.webservicex.net site to query the weather forecast.

package com.android.weather;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;

public class MyAndroidWeatherActivity extends Activity {
    //Define the content source address that needs to be obtained
    private static final String SERVER_URL =
        "http://www.webservicex.net/WeatherForecast.asmx/GetWeatherByPlaceName";
    
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.main);
        
        HttpPost request = new HttpPost(SERVER_URL); //Create an Http request based on the content source address
        // add a variable
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // set a region name
        params.add(new BasicNameValuePair("PlaceName", "NewYork")); //Add required parameters
        
        
        try {
            //Set the encoding of the parameter
            request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            // send request and get feedback
            HttpResponse httpResponse = new DefaultHttpClient().execute(request);
             
            // Parse the returned content
            if(httpResponse.getStatusLine().getStatusCode() != 404){
               String result = EntityUtils.toString(httpResponse.getEntity());
               System.out.println(result);
            }
        } catch (Exception e) {
            e.printStackTrace ();
       }
    }
}

 Don't forget to set access network permissions in the configuration file:

 

<uses-permission android:name="android.permission.INTERNET" />  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326394695&siteId=291194637