androidhttpclientandroid-async-httploopjasynchttpclient

Implement Basic HttpClient Post with Loopj on Android


I am new to Android programming and am having some difficulty implementing a basic version of a message sender using the Loopj library.

Here is my code:

package com.test.app;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.loopj.android.http.*;

import org.apache.http.Header;

public class Test extends AppCompatActivity {

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

        AsyncHttpClient client = new AsyncHttpClient();
        client.get("https://www.google.com", new AsyncHttpResponseHandler() {

            @Override
            public void onStart() {
                // called before request is started
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[]     response) {
                // called when response HTTP status is "200 OK"
           }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
                //called when response HTTP status is "4XX" (eg. 401, 403, 404)
            }

            @Override
            public void onRetry(int retryNo) {
                // called when request is retried
            }
        });

    }

}

This code gives me two errors I am trying to work through:

  1. The line AsyncHttpClient client = new AsyncHttpClient(); underlines AsyncHttpClient and reports and error: "Class must either be declared abstract or implement abstract method for onFailure"

  2. The @Override designation for onSuccess and onFailure is underlined and the error states "The method does not override the method from its superclass".

How can I make this work in my Android Activity?


Solution

  • This is because of wrong imports.

    You should replace:

    import org.apache.http.Header;
    

    with

    import cz.msebera.android.httpclient.Header;
    

    UPDATE:

    BTW if you want to make HTTP POST you should use .post() instead of .get()