【问题标题】:Android POST connection timeoutAndroid POST 连接超时
【发布时间】:2018-10-27 02:43:21
【问题描述】:

我正在尝试进行 POST 连接,但它不起作用。错误是“连接超时”。 我发送一个字符串并接收另一个字符串,post 参数是“quest”。 服务器工作正常。我已经完成了为 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

【问题讨论】:

  • 能否请您发布来自您的客户端代码的堆栈跟踪?
  • 切换到Retrofit 会让您的任务更轻松。
  • 是的,我知道改造会容易得多,但我想先学习这种方法。
  • 我认为您的参数可能编码错误。假设“params[0] 包含一个字符串“tom”,那么您将是 urlParameters = “quest%3Dtom”,但您想要的可能是“quest=tom”。所以您需要像这样对每个部分进行编码:: String part1 = URLEncoder.encode("quest", "UTF-8"); String part2 = URLEncoder.encode(params[0], "UTF-8"); 然后 String urlParameters = part1 + "=" + part2;
  • 尝试将超时设置得更长,例如 READ_TIMEOUT = 60000;和 CONNECTION_TIMEOUT = 60000;

标签: java android post httpconnection


【解决方案1】:

这是我刚刚从功能齐全的代码中获取的一个工作示例,所以这应该可以工作。

只需创建一个方法来处理您的请求:

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;
}

现在只需从AsyncTask 或后台线程中调用makeHttpRequest() 方法,如下所示:

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

.

注意:方法makeHttpRequest()必须从AsyncTask或后台线程调用,否则会报错!

另请注意,您的“stringUrl”应该指向一些脚本,例如 PHP!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-17
    • 2016-10-02
    • 2012-09-28
    相关资源
    最近更新 更多