POST-запрос вызывает метод doGet - PullRequest
3 голосов
/ 20 февраля 2012

Я отправляю запросы Post на сервлет Tomcat, который я быстро перерыл вместе. Когда я делаю запрос HttpPost на Android, я вижу, что вижу запрос в сервлете, но это потому, что вызывается метод doGet. Может кто-нибудь объяснить мне, почему это происходит и как я могу это исправить, чтобы вызвать метод doPost?

Вот способ обслуживания, выполняющий почтовый запрос:

@Override
protected void onHandleIntent(Intent intent) {
    Log.i(TAG, "handling intent");
    // get Longitude and Latitude
    Bundle bundle = intent.getExtras();

    double longitude = bundle.getDouble("longitude");
    double latitude  = bundle.getDouble("latitude");
    // int  id = bundle.getInt("id");
    long time = System.currentTimeMillis();

    // log location in local db

    // send location up to db repository (repositories)
    JSONObject jObj = new JSONObject();
    try {
        jObj.put("long", longitude);
        jObj.put("lat", latitude);
        jObj.put("userId", 1);
        jObj.put("time", time);

        Log.i(TAG, "JSON object: " + jObj.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }

    try {
        StringEntity se = new StringEntity("JSON" + jObj.toString());
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        String url = [http://url/to/servlet/here];
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.setEntity(se);
        HttpResponse response;

        response = httpClient.execute(post);

        // check response
        if (response != null) {
            Log.i(TAG, "Message received");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

И сервлет, получивший запрос:

public class ReceiveLocation extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Post request received");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        try {
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = request.getReader().readLine()) != null) {
                sb.append(s);
            }
            System.out.println("sb: " + sb.toString());
       } catch (Exception e) {
           e.printStackTrace();
       }
    }


/**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws         ServletException, IOException {
        processRequest(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Get request received!!!");
    }
}

Вывод «Получить запрос получен !!!»

EDIT

Я временно изменил метод doGet, чтобы дать мне представление о нескольких вещах, которые я считаю важными (я новичок во всем этом, пожалуйста, дайте мне знать, если то, что я опубликовал, не помогает в этой ситуации) .

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Get request received!!!");
    Enumeration<String> enumerator = request.getHeaderNames();
    while (enumerator.hasMoreElements()) {
        System.out.println("header: " + enumerator.nextElement());
    }

    System.out.println("Method request: " + request.getMethod().toString());
    Enumeration<String> attrEnumerator = request.getAttributeNames();
    while (attrEnumerator.hasMoreElements()) {
        System.out.println("attr:" + attrEnumerator.nextElement());
    }
    Enumeration<String> paramEnumerator = request.getParameterNames();
    while (paramEnumerator.hasMoreElements()) {
        System.out.println("param:" + paramEnumerator.nextElement());
    }
}

Выход:

Получить запрос полученный !!!

заголовок: хост

заголовок: соединение

header: user-agent

Запрос метода: GET

Output from Android:
 I TreasureHuntActivity: Provider network has been selected.
 I TreasureHuntActivity: Init Lat: 30280
 I TreasureHuntActivity: Init Long: -97744
 I SendLocationIntentService: handling intent
 I SendLocationIntentService: JSON object: {"long":0,"time":1329792722150,"lat":0}
 I SendLocationIntentService: Method POST
 I SendLocationIntentService: Entity java.io.ByteArrayInputStream@4058d760
 I SendLocationIntentService: handling intent
 I SendLocationIntentService: JSON object: {"long":0,"time":1329792743161,"lat":0}
 I SendLocationIntentService: Method POST
 I SendLocationIntentService: Entity java.io.ByteArrayInputStream@40594050

1 Ответ

1 голос
/ 20 февраля 2012

Вы не выполняете HTTP POST со своими кодами, потому что ваша сущность пуста.

Вот пример одного из способов сделать HTTP POST в Android

...