簡體   English   中英

如何將POST請求從Android發送到Elasticsearch

[英]How to send POST request from Android to Elasticsearch

我有一個應用程序,用戶輸入的“反饋”存儲為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


        }

我該如何運作?

謝謝!

您可以使用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

嘗試對API調用進行改造。 很簡單

將以下依賴項添加到應用程序級別gradle文件中。

    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'

首先制作改造對象。 在此類中,定義基本URL和其他設置。

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

使api調用的接口。

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

}

使您的服務器響應json創建pojo類。

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

}

您曾為robopojo插件使用create pojo類。

以這種方式將api調用為片段或活動。

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

        }
    });

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM