Почему HTTP-запрос не работает? Вит.ай

Я хочу, чтобы wit.ai анализировал мои предложения. Когда я отправляю строку «где находится дверь», wit.ai должен ответить JSON, который включает в себя то, что мое предложение имеет намерение: навигация. Но, к сожалению, журнал wit.ai говорит, что входящих запросов нет. Что я делаю не так? Параметры правильные, но может быть они в ложном порядке?

public class MainActivity extends AppCompatActivity {

    String addressM = "https://api.wit.ai/message";
    String accessToken = "xxxxxxxxxxxxxxxxxxxxccc";
    String header = "Authorization: Bearer ";
    String query = "q";
    String message = "where is the door";


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


        final Button button = (Button) findViewById(R.id.button);
        final TextView textView = (TextView) findViewById(R.id.textView);


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new JSONTask().execute(addressM);
            }
        });

    }

    private class JSONTask extends AsyncTask<String, String, String >{
        @Override
        protected String doInBackground(String... params) {

            HttpURLConnection connection = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestProperty("access_token", "xxxxxxxxxxxxxxxxxxxxxxx");
                connection.setRequestProperty("q", message);
                connection.setRequestMethod("POST");
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();

                String line = "";
                while ((line = reader.readLine()) !=null){
                    buffer.append(line);
                }
                return buffer.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null){
                    connection.disconnect();
                }
                try {
                    if (reader != null){
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            TextView textView = (TextView) findViewById(R.id.textView);
            textView.setText(result);
            Toast.makeText(MainActivity.this, result,
                    Toast.LENGTH_LONG).show();
        }
    }

}

Вот пример, какой должен быть ответ. Для меня важно, что целью является навигация

  [
    {
    "entities":
    {
    "intent":
    [
    {
    "confidence":
    0.92597581019421
    "value":
    {
    "value":
    "navigation"
    }
    "entity":
    "intent"
    }
    ]
    }
    "confidence":
    null
    "_text":
    "where is the door"
    "intent":
    "default_intent"
    "intent_id":
    "default_intent_id"
    }
    ]

person Community    schedule 10.04.2018    source источник
comment
Токен носителя или access_token в качестве требуемого параметра? Потому что у тебя есть и то, и другое. Какой код ответа HTTP и тело от wit.ai?   -  person evilSnobu    schedule 10.04.2018
comment
Вы можете отредактировать этот вопрос, чтобы удалить конфиденциальную информацию (ключ доступа)   -  person Hristo Vrigazov    schedule 10.04.2018
comment
@evilSnobu Я пробовал оба, и ничего не получилось, т. к. я не знаю, что мне взять.   -  person    schedule 10.04.2018
comment
Посмотрите страницу документа https://wit.ai/docs/http/20170307.   -  person evilSnobu    schedule 10.04.2018
comment
Я добавил пример ответа   -  person    schedule 10.04.2018


Ответы (1)


Вы должны передавать параметры как параметры запроса, а не как заголовки HTTP. Также токен доступа должен быть передан в HTTP-заголовке authorization.

Попробуй это:

Uri uri = Uri.parse(addressM)
  .buildUpon()
  .appendQueryParameter("q", message)
  .build();
URL url = new URL(uri.toString());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Bearer " + myAccessToken);
connection.setRequestMethod("POST");
connection.connect();

Если вы хотите упростить свою жизнь с помощью HTTP API, рассмотрите возможность модернизации (я не пытался проверить, совместим ли Wit API с ним) или, по крайней мере, попробуйте OkHttp.

static final String MESSAGE_BASE_URL = "https://api.wit.ai/message";
static final String MY_ACCESS_TOKEN = "...";

private final OkHttpClient client = new OkHttpClient();

...
HttpUrl url = HttpUrl.parse(MESSAGE_BASE_URL)
  .newBuilder()
  .addQueryParameter("q", message)
  .build();
Request request = new Request.Builder()
  .url(url)
  .addHeader("authorization", "Bearer " + MY_ACCESS_TOKEN)
  .build();
Response response = client.newCall(request).execute();
return response.body().string();
person orip    schedule 10.04.2018