Тайм-аут соединения Android POST - PullRequest
0 голосов
/ 17 мая 2018

Я пытаюсь установить POST-соединение, но оно не работает.Ошибка «время ожидания соединения».Я отправляю строку и получаю другую строку, а параметр post - "квест".Сервер работает нормально.Я сделал тесты загрузки сайта для POST-соединений, и все это работает.Я думаю, что проблема на стороне Android, потому что я впервые пытаюсь установить POST-соединение.

Также на стороне сервера находится Node.js с обработкой фреймворка Express с вызовом на /search.

Вот код Java:

public class DownloadDados extends AsyncTask<String, Void, String> { 
    public static final String REQUEST_METHOD = "POST";
    public static final int READ_TIMEOUT = 20000;
    //public static final String charset = "UTF-8";
    public static final int CONNECTION_TIMEOUT = 20000;

    @Override
    protected void onPreExecute(){
        //Log.i(TAGAsync, "ON PRE EXECUTE");
        //Toast.makeText(TAGAs,"Buscando Servidor", Toast.LENGTH_LONG).show();
    }

    @Override
protected String doInBackground(String... params) {
        // params[0] an string
        String stringUrl = "http://XXX.XXX.XX.XX:3000/search"; //blocked for security reasons
        String quest = "quest="+params[0]; //enter the parameter
        int responseCode = 0;
        String result;
        String inputLine;

        try{
            URL myUrl = new URL(stringUrl);

            HttpURLConnection connection =(HttpURLConnection) myUrl.openConnection();

            connection.setRequestMethod(REQUEST_METHOD);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setConnectTimeout(CONNECTION_TIMEOUT);
            connection.setRequestProperty("Accept-Charset", "UTF-8");

            //connection.connect();

            String urlParameters = URLEncoder.encode(quest, "UTF-8");
            connection.setDoOutput(true);
            DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());

            dStream.writeBytes(urlParameters);
            dStream.flush();
            dStream.close();

            responseCode = connection.getResponseCode();

            InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());

            BufferedReader reader = new BufferedReader(streamReader);
            StringBuilder stringBuilder = new StringBuilder();

            while((inputLine = reader.readLine()) != null){
                stringBuilder.append(inputLine);
            }

            reader.close();
            streamReader.close();

            result = stringBuilder.toString();
        }
        catch(IOException e){
            Log.i(TAGAsync, "URL: "+ stringUrl + " Error: " + e.getMessage() + " responseCode: " + responseCode);
            //Toast.makeText(TAGAs,"Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
            result = null;
        }

        return result;
    }

Мне было интересно, есть ли ошибка в моем коде Java.Может кто-нибудь помочь?

Редактировать:

05/16 21:39:03: Launching app
$ adb install-multiple -r -t -p com.bizzo.speech4beef C:\Users\Bizzo\AndroidStudioProjects\Speech4Beef\app\build\intermediates\split-apk\debug\slices\slice_1.apk 
Split APKs installed
$ adb shell am start -n "com.bizzo.speech4beef/com.bizzo.speech4beef.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Connected to process 23492 on device asus-asus_x00ld-HAAXB602M664EG3
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/System: ClassLoader referenced unknown path: /data/app/com.bizzo.speech4beef-1/lib/arm64
I/InstantRun: starting instant run server: is main process
V/Monotype: SetAppTypeFace- try to flip, app = com.bizzo.speech4beef
V/Monotype:     Typeface getFontPathFlipFont - systemFont = default#default
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
V/Monotype: SetAppTypeFace- try to flip, app = com.bizzo.speech4beef
                Typeface getFontPathFlipFont - systemFont = default#default
V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
                  mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
                  mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
                  mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@c812720
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@fa998d9
W/AbstractGoogleClient: Application name is not set. Call Builder#setApplicationName.
I/Adreno: QUALCOMM build                   : c5b7903, Ic4cf336e0a
          Build Date                       : 02/17/17
          OpenGL ES Shader Compiler Version: XE031.09.00.04
          Local Branch                     : 
          Remote Branch                    : 
          Remote Branch                    : 
          Reconstruct Branch               : 
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@901f80d
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/AsyncTask: URL: http://<--ComputerIP-->:3000/search Error: Connection timed out responseCode: 0
I/AsyncTask: Error to download data: main

1 Ответ

0 голосов
/ 17 мая 2018

Вот рабочий пример, который я только что взял из полнофункционального кода, поэтому он должен работать.

Просто создайте метод для обработки вашего запроса:

public String makeHttpRequest(Map<String, String> params){
    String result = "";
    InputStream responseStream = null;

    String logMess = "";
    long startTime;
    long stopTime;
    long elapsedTime;

    try {
        startTime = System.currentTimeMillis();

        StringBuilder postData = new StringBuilder();
        for(Map.Entry<String, String> param : params.entrySet()){
            if(postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        byte[] postDataBytes = postData.toString().getBytes("UTF-8");
        //This should be addressing some script like PHP something like search.php
        String stringUrl = "http://XXX.XXX.XX.XX:3000/search"; 
        URL myUrl = new URL(stringUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Cache-Control", "no-cache");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));

        DataOutputStream request = new DataOutputStream(conn.getOutputStream());
        request.write(postDataBytes);
        request.flush();
        request.close();

        //Check the response code of the server -
        Integer replyCode = conn.getResponseCode();
        logMess += "   Reply Code:  " + replyCode.toString();

        responseStream = new BufferedInputStream(conn.getInputStream());
        BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));

        stopTime = System.currentTimeMillis();
        elapsedTime = stopTime - startTime;
        logMess += "   elapsed Time :  " + elapsedTime + " ms";

        // Of course you do not need to do a time measurement, but it might be interesting 
        Log.d(TAG, "makeHttpRequest --- " + logMess);
        String line = "";
        StringBuilder stringBuilder = new StringBuilder();

        while ((line = responseStreamReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        responseStreamReader.close();

        result = stringBuilder.toString();
    }
    catch (UnsupportedEncodingException e) {
        Log.e(TAG, "makeHttpRequest --- " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "makeHttpRequest --- " + e.getMessage());
    }
    return result;
}

Теперь просто вызовите метод makeHttpRequest() из AsyncTask или фонового потока, например:

Map<String, String> paramList = new LinkedHashMap<String, String>();
paramList.put("quest", params[0]);
String requestResult = makeHttpRequest(paramList);

.

Примечание: метод makeHttpRequest() должен вызываться из AsyncTask или фонового потока, в противном случае вы получите ошибку!

.

Также обратите внимание, что ваш "stringUrl" должен указывать на некоторый скрипт, такой как PHP!

...