【问题标题】:POST JSONArray to server using HttpUrlConnection使用 HttpUrlConnection 将 JSONArray POST 到服务器
【发布时间】:2016-12-18 11:08:09
【问题描述】:

我需要将我的 JSONArray 发布到服务器,我尝试了 HttpUrlConnection 但我不知道如何在我的情况下使用 ASyncTask。

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

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

【问题讨论】:

    标签: java android json rest post


    【解决方案1】:

    坦率地说,ASyncTask 是老式的并且有很多样板代码。您需要切换到 Retrofit,这是用作 HTTP 客户端的最佳库。试一试,你永远不会回头。以下是您在 Retrofit 中执行此操作的方法。

    这就是您在 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 主体中的服务器,您需要做两件事。首先定义如下

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

    在你的活动中你使用它如下

    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 活动都在上述调用中处理。就这么简单。

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

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

    【讨论】:

    • 我不懂 User 类。
    • 用户类是一个简单的 POJO。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    相关资源
    最近更新 更多