如何将POST请求从Android发送到Elasticsearch

时间:2018-11-05 05:35:41

标签: android json elasticsearch android-volley

我有一个应用程序,用户输入的“反馈”存储为JSONObject。如何将此JSONObject发送到elasticsearch?

下面是我尝试过的代码:

     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


        }

我如何使其工作?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以使用HashMap存储数据,然后将其转换为JSONObject。之后,通过该JSONObject请求:

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

答案 1 :(得分:-1)

尝试对API调用进行改造。很简单。

将以下依赖项添加到应用程序级别的gradle文件中。

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;
}
}

首先制作改造对象。在此类中,定义基本网址和其他设置。

ApiClient.java

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

用于api调用的make接口。

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;
}

}

使您的服务器响应json创建类似pojo的类。

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

        }
    });

}

您使用了 robopojo 插件的create pojo类。

以这种方式将api称为片段或活动。

 adapter1.notifyDataSetChanged();
 adapter2.notifyDataSetChanged();
 adapter3.notifyDataSetChanged();

更多信息请参考此链接 https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/ https://square.github.io/retrofit/