POST JSONArray to server using HttpUrlConnection

2019-07-25 05:59发布

I need to post my JSONArray to server, i tried HttpUrlConnection but i don't know how to use ASyncTask in my case.

In my onLocationChanged method, I need to post that JSON every 10 seconds. Does anyone know how to do this?

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

    private final String LOG_TAG = "iTrackerTestApp";
    private TextView txtLatitude, txtLongitude, txtAltitude, txtVelocidade;
    private GoogleApiClient mGoogleApiClient;
    private HttpURLConnection urlConnection = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        txtLatitude = (TextView) findViewById(R.id.txtLatitude);
        txtLongitude = (TextView) findViewById(R.id.txtLongitude);
        txtAltitude = (TextView) findViewById(R.id.txtAltitude);
        txtVelocidade = (TextView) findViewById(R.id.txtVelocidade);
    }

    @Override
    public void onConnected(Bundle bundle) {
        LocationRequest mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(1000); // Atualiza a localização a cada segundo.
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.i(LOG_TAG, location.toString());

        txtLatitude.setText("Latitude: " + Double.toString(location.getLatitude()));
        txtLongitude.setText("Longitude: " + Double.toString(location.getLongitude()));
        if(location.hasAltitude())
            txtAltitude.setText("Altitude: " + Double.toString(location.getAltitude()));
        if(location.hasSpeed())
            txtVelocidade.setText("Velocidade: " + Float.toString(location.getSpeed()));

        final JSONArray array = new JSONArray();
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("Latitude", txtLatitude.getText());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            jsonObject.put("Longitude", txtLongitude.getText());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        array.put(jsonObject);

        // I NEED TO SEND THIS JSON TO SERVER EVERY 10 SECONDS
    }

    @Override
    protected void onStart(){
        super.onStart();
        mGoogleApiClient.connect();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    protected  void onStop(){
        mGoogleApiClient.disconnect();
        super.onStop();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(LOG_TAG, "Conexão com o GoogleApiClient suspensa!");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(LOG_TAG, "Conexão com o GoogleApiClient falhou!");
    }
}

1条回答
仙女界的扛把子
2楼-- · 2019-07-25 06:45

To be frank, ASyncTask is old style and a lot of boiler plate coding. You need to switch to Retrofit, which is the best library to be used as a HTTP client. Give it a shot, and you will never turn back. Here is how you do this in Retrofit.

This is how you define your end points in Retrofit

public static final String BASE_URL = "http://api.myservice.com/";
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

Then to send your JSON to server in the body of the REST API you do two things. First define it as below

public interface MyApiEndpointInterface
{
    @POST("users/new")
    Call<User> createUser(@Body User user);
}

And in your activity you use it as below

User user = new User(123, "John Doe");
Call<User> call = apiService.createuser(user);
call.enqueue(new Callback<User>() {
  @Override
  public void onResponse(Call<User> call, Response<User> response) {
  }

  @Override
  public void onFailure(Call<User> call, Throwable t) {
  }

All your AsyncTask activity is handled in the above call. It's as simple as that.

Above call will send the below JSON to your server

{"name":"John Doe","id":123}
查看更多
登录 后发表回答