Http клиент в Java 8 - PullRequest
       7

Http клиент в Java 8

0 голосов
/ 13 апреля 2020

Мне нужно встроить http-клиента в java 8, который отправляет запросы на node.js сервер. У меня проблемы с клиентом, потому что возвращает ошибку 404. Я думаю, что проблема в запросе.

Сервер работает, потому что я проверил его с помощью этого запроса curl (правильно отвечает со статусом 200):

curl --request GET \
  --url http://localhost:4000/ \
  --header 'content-type: application/x-www-form-urlencoded' \
  --data position=6 \
  --data id=2

Может кто-нибудь помочь мне, пожалуйста?

Код клиента

String result = new String();
String requestBody = new String();
try {

    JSONObject requestJson =  new JSONObject();
    requestJson.put("id","2");
    requestJson .put("position","6");
    requestBody = requestJson.toString();

    byte[] body = requestBody.getBytes(StandardCharsets.UTF_8);
    URL url = new URL("http://localhost:4000");
    HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
    httpURLConnection.setRequestMethod("GET");
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    OutputStream outputStream = httpURLConnection.getOutputStream();
    outputStream.write(body);
    outputStream.flush();
    outputStream.close();

    int responseCode = httpURLConnection.getResponseCode();

    if(responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
        BufferedReader inputStream = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while((inputLine = inputStream.readLine()) != null) {
            response.append(inputLine);
        }
        inputStream.close();

        result = "" + responseCode + " " + response.toString();
    } else {
        result = "" + responseCode;
    }

} catch(Exception e) {
    result = result + e.toString();
}

System.out.println(result);

Код сервера

var express = require('express')
var app = express()
const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))

app.get('/', (req, res) => {
   const id = req.body.id
   const position = req.body.position

   let distance

   if (id == 1) {
      distance = 0 - position
   } else if (id == 2) {
      distance = 10 - position
   } else if (id == 3) {
      distance = 20 - position
   }
   distance = Math.abs(distance)
   res.json(distance)   
})

app.listen(4000, () => {
   console.log("Server running on port 4000")
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...