How to send POST request from Android to Elasticsearch

3820 views android
1

I have an app, where the 'Feedback' entered by the user is stored as JSONObject. How do I send this JSONObject to elasticsearch?

Below is the code I have tried:

     void sendFeedback() {
            String url = "http://localhost:9200/trial_feedback_index2/trial_feedback_type2 ";

/* "trial_feedback_index2" is my index and "trial_feedback_type2" is my type, where I want to store the data,  in elasticsearch.*/

            JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>()
            {
                @Override
                public void onResponse(JSONObject response) {

                    Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();

                    Log.d("Response", response.toString());
                    Toast.makeText(getApplicationContext(),response.toString(), Toast.LENGTH_SHORT).show();
                }
            },
                    new Response.ErrorListener()
                    {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // error
                            // Log.d("Error.Response", response);
                        }
                    }
            ) {
                @Override
                protected Map<String, String> getParams()
                {
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("Feedback", feedbackQAJsonObjOuter.toString());


                    return params;
                }
            };
            queue.add(postRequest);
    // add it to the RequestQueue


        }

How do I make it work?

Thanks!

answered question

http://localhost:9200/ will not work. That needs to be the external IP of your server, but you've given localhost of your Android device, not running Elasticsearch

2 Answers

2

You can use HashMap to store your data and then convert it to JSONObject. After that pass that JSONObject to request:

HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("feedbackKey","value");
JSONObject jsonObject = new JSONObject(hashMap);

JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>()
            {..... 
..... Your other code

posted this
5

Try retrofit for api calling. it easy.

Add below dependency into app level gradle file..

    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'

First make retrofit object. In this class define base url and other setup.

ApiClient.java

public class ApiClient {
private final static String BASE_URL = "https://simplifiedcoding.net/demos/";

public static ApiClient apiClient;
private Retrofit retrofit = null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}



private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}
}

make interface for api calling.

public interface ApiInterface {
@GET("marvel/")
Call<List<Hero>> getHero();

// here pass url path user class has input for email and password. and pass your server response class.
@POST("login/")
Call<ResponseData> doLogin(@Body User user);

}

make your server response json create pojo class like..

public class Hero {
@SerializedName("name")
@ColumnInfo(name="sName")
private String name;
@SerializedName("realname")
private String realname;
@SerializedName("team")
private String team;
@SerializedName("firstappearance")
private String firstappearance;
@SerializedName("createdby")
private String createdby;
@SerializedName("publisher")
private String publisher;
@SerializedName("imageurl")
private String imageurl;
@SerializedName("bio")

private String bio;


public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getRealname() {
    return realname;
}

public void setRealname(String realname) {
    this.realname = realname;
}

public String getTeam() {
    return team;
}

public void setTeam(String team) {
    this.team = team;
}

public String getFirstappearance() {
    return firstappearance;
}

public void setFirstappearance(String firstappearance) {
    this.firstappearance = firstappearance;
}

public String getCreatedby() {
    return createdby;
}

public void setCreatedby(String createdby) {
    this.createdby = createdby;
}

public String getPublisher() {
    return publisher;
}

public void setPublisher(String publisher) {
    this.publisher = publisher;
}

public String getImageurl() {
    return imageurl;
}

public void setImageurl(String imageurl) {
    this.imageurl = imageurl;
}

public String getBio() {
    return bio;
}

public void setBio(String bio) {
    this.bio = bio;
}

}

you used create pojo class for robopojo plugin.

for calling api into fragment or activity like this way..

    ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
    Call<List<Hero>> herodata = apiInterface.getHero();
    herodata.enqueue(new Callback<List<Hero>>() {
        @Override
        public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
            if (response.isSuccessful() && response != null && response.body() != null) {

            }
        }

        @Override
        public void onFailure(Call<List<Hero>> call, Throwable t) {
            Log.d("Error", t.getMessage());

        }
    });

more information refer this link https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/ https://square.github.io/retrofit/

posted this

Have an answer?

JD

Please login first before posting an answer.