Kai Wang
Kai Wang

Reputation: 3361

OKHttp3 post method keeps return 404 error

I want to do POST with OKHttp3, but it keeps returning 404. Is there anything wrong with my code? The server side keeps telling me that the url and json are correct.

I have tried another post url and json, it works, return code 200.

package com.epsfamily.www.kaipostb;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.IOException;
import java.util.logging.Logger;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    OkHttpClient client = new OkHttpClient();

    public static final MediaType JSON
            = MediaType.parse("application/json; charset=utf-8");

    String url;


    // test data
    String bowlingJson(String player1, String player2) {
        return "{ \"deviceId\": \"1abcd\", \"buildingId\": 2, \"isRoutingOptimized\": false, \"isFromCurrentLocation\": true, \"startPoint\": 1, \"destinations\": [ 3, 4 ], \"createdAt\": \"2016-02-19T20:08:45.308Z\" } ";
    }

    String doPostRequest(String url, String json) throws IOException {
        com.orhanobut.logger.Logger.json(json);
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        com.orhanobut.logger.Logger.v("code: " + response.code());

        return response.body().string();
    }

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

        url = "http://54.86.18.109:5080/Routing";

        new PostAsync().execute();
    }

    public class PostAsync extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String json = bowlingJson("Jesse", "Jake");
            String postResponse = null;
            try {
                postResponse = doPostRequest(url, json);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("res: " + postResponse);

            return postResponse;
        }
    }

}

Upvotes: 3

Views: 2747

Answers (2)

Kai Wang
Kai Wang

Reputation: 3361

Finally, found that server gave me the wrong url. it should be "http://54.86.18.109:5080/api/Routing".

Thank you guys for trying...

Upvotes: 1

JoKr
JoKr

Reputation: 5266

Go here: http://54.86.18.109:5080/Routing

What you get? It's 404. Check again url.

EDIT: ok, it's POST, but i still get 404 with POST request.

Upvotes: 2

Related Questions