其他分享
首页 > 其他分享> > android-OKHttp3发布方法不断返回404错误

android-OKHttp3发布方法不断返回404错误

作者:互联网

我想使用OKHttp3进行POST,但它始终返回404.我的代码有什么问题吗?服务器端不断告诉我url和json是正确的.

我尝试了另一个发布网址和json,它可以正常工作,返回码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;
        }
    }

}

解决方法:

去这里:http://54.86.18.109:5080/Routing

你得到什么?是404.再次检查网址.

编辑:好的,它是POST,但是我仍然可以通过POST请求获得404.

标签:http-status-code-404,okhttp,android
来源: https://codeday.me/bug/20191119/2032826.html