ttpUrlConnection将JSONArray发布到服务器

ttpUrlConnection将JSONArray发布到服务器

本文介绍了使用HttpUrlConnection将JSONArray发布到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将JSONArray发布到服务器,我尝试了HttpUrlConnection,但是我不知道如何使用ASyncTask.

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

在我的onLocationChanged方法中,我需要每10秒发布一次JSON.有人知道该怎么做吗?

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!");
    }
}

推荐答案

坦率地说,ASyncTask是旧样式,并且有很多样板代码.您需要切换到Retrofit,这是用作HTTP客户端的最佳库.试一试,您将永远不会回头.这是您在翻新中的操作方式.

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();

然后将JSON发送到REST API主体中的服务器,您需要做两件事.首先将其定义如下

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) {
  }

您的所有AsyncTask活动都在上述调用中处理.就这么简单.

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

上述调用会将以下JSON发送到您的服务器

Above call will send the below JSON to your server

{"name":"John Doe","id":123}

这篇关于使用HttpUrlConnection将JSONArray发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 18:44