在Android应用程序上从服务器获取响应时出现意外状态行

时间:2018-02-07 17:24:43

标签: java android http client-server esp8266

我正在Android应用和ESP8266 NodeMCU-1.0之间建立服务器 - 客户端通信。 ESP正在指定的网络上创建服务器,移动设备正在连接到同一网络。

出于测试目的,我按下发送按钮时发送“try123”字符串。并在IDE的串行监视器上接收适当的响应(即在服务器上接收数据)。但是服务器响应是“Test_successful”字符串。我使用client.print将此字符串发送给客户端。在应用程序中,我正在烘烤服务器响应。

问题是,如果我使用本地生成的URL使用浏览器发出HTTP请求,则可以看到响应“Test_successful”。但是在app toast中它显示为空,而在调试时它显示错误意外的行状态。

ESP代码(服务器端):

#include <ESP8266WiFi.h>    
const char* ssid = "DARSHAN95";
const char* password = "12345678";
//const char* ssid = "TP-LINK_42C148";
//const char* password = "";
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);  
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  // Start the server
  server.begin();
  Serial.println("Server started");
  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  // Match the request
  //client.flush();

  delay(100);
   // Send the response to the client
client.print("Test_Sucessfull");
  delay(200);
  Serial.println("Client disonnected");
}

Android应用程序代码:
请忽略它及其代码上的文本输入块。

package com.example.access.test123;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {
    EditText Message;
    Button Send;
    String data;
    HttpURLConnection http;
    String sendingMessage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Message = (EditText) findViewById(R.id.message);
        Send = (Button) findViewById(R.id.send);
        Send.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpAsync task = new HttpAsync();
                task.execute();
            }
        });
    }


    public void sendDataMethod() throws UnsupportedEncodingException{
        sendingMessage = Message.getText().toString();
        String data = "Error";
        BufferedReader reader = null;
        //Sending Data
        try{

            String ip = "http://192.168.43.76/?try123";
            //String address = ip + sendingMessage;
            //URL url = new URL(address);
            URL url = new URL(ip);
            URLConnection conn = url.openConnection();
            http = (HttpURLConnection)conn;
            http.setRequestMethod("POST"); // PUT is another valid option
            http.setDoOutput(true);
            http.setDoInput(true);

            //Server Response
            int i =  http.getResponseCode();
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null){
                sb.append(line + "\n");
            }
            data = sb.toString();
        }

            catch(IOException e){;
            Log.d("Error2", e.toString());

        }
        finally {
            try{
                if(reader != null) {
                    reader.close();
                }
            }
            catch (IOException ex){
                Log.d("Error3", ex.toString());

            }
        }
    }
    private class HttpAsync extends AsyncTask {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object[] objects) {
            try {
                sendDataMethod();
            }
            catch (UnsupportedEncodingException e) {
                Log.d("Error", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
        }
    }
}

调试结果:

02/07 22:40:23: Launching app
$ adb install-multiple -r -t A:\New folder\Test123\app\build\intermediates\split-apk\debug\dep\dependencies.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_1.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_2.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_3.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_6.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_9.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_8.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_7.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_4.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_5.apk A:\New folder\Test123\app\build\intermediates\split-apk\debug\slices\slice_0.apk A:\New folder\Test123\app\build\outputs\apk\debug\app-debug.apk 
Split APKs installed
$ adb shell am start -n "com.example.access.test123/com.example.access.test123.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Waiting for application to come online: com.example.access.test123.test | com.example.access.test123
Connecting to com.example.access.test123
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8601', transport: 'socket'
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1436)
W/System: ClassLoader referenced unknown path: /data/app/com.example.access.test123-2/lib/arm64
I/art: Starting a blocking GC HeapTrim
I/InstantRun: starting instant run server: is main process
I/art: Starting a blocking GC Instrumentation
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/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = null, this = DecorView@3280086[]
D/WindowClient: Add to mViews: DecorView@3280086[MainActivity], this = android.view.WindowManagerGlobal@d5cc9ee
D/OpenGLRenderer: Dumper init 4 threads <0x7c6a19ee40>
D/OpenGLRenderer: <com.example.access.test123> is running.
D/OpenGLRenderer: CanvasContext() 0x7c6773f880
D/ViewRootImpl[MainActivity]: hardware acceleration is enabled, this = ViewRoot{500151c com.example.access.test123/com.example.access.test123.MainActivity,ident = 0}
V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = ViewRoot{500151c com.example.access.test123/com.example.access.test123.MainActivity,ident = 0}, this = DecorView@3280086[MainActivity]
D/OpenGLRenderer: CanvasContext() 0x7c6773f880 initialize window=0x7c73e55e00, title=com.example.access.test123/com.example.access.test123.MainActivity
D/Surface: Surface::allocateBuffers(this=0x7c73e55e00)
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/OpenGLRenderer: Created EGL context (0x7c6a19f600)
D/OpenGLRenderer: ProgramCache.init: enable enhancement 1
I/OpenGLRenderer: Get disable program binary service property (0)
I/OpenGLRenderer: Initializing program atlas...
I/ProgramBinary/Service: ProgramBinaryService client side disable debugging.
I/ProgramBinary/Service: ProgramBinaryService client side disable binary content debugging.
D/ProgramBinary/Service: BpProgramBinaryService.getReady
D/ProgramBinary/Service: BpProgramBinaryService.getProgramBinaryData
I/OpenGLRenderer: Program binary detail: Binary length is 249276, program map length is 124.
I/OpenGLRenderer: Succeeded to mmap program binaries. File descriptor is 74, and path is /dev/ashmem.
I/OpenGLRenderer: No need to use file discriptor anymore, close fd(74).
D/OpenGLRenderer: Initializing program cache from 0x0, size = -1
D/MALI: eglCreateImageKHR:513: [Crop] 0 0 896 1344  img[896 1344] 
D/Surface: Surface::connect(this=0x7c73e55e00,api=1)
W/libEGL: [ANDROID_RECORDABLE] format: 1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
D/OpenGLRenderer: CacheTexture 3 upload: x, y, width height = 0, 0, 189, 441
D/OpenGLRenderer: ProgramCache.generateProgram: 0
D/OpenGLRenderer: ProgramCache.generateProgram: 34359738371
D/OpenGLRenderer: ProgramCache.generateProgram: 5242945
D/OpenGLRenderer: ProgramCache.generateProgram: 5242944
D/OpenGLRenderer: ProgramCache.generateProgram: 240518168576
D/OpenGLRenderer: ProgramCache.generateProgram: 68724719680
V/InputMethodManager: onWindowFocus: android.support.v7.widget.AppCompatEditText{8687c92 VFED..CL. .F....ID 228,66-851,212 #7f070042 app:id/message} softInputMode=288 first=true flags=#81810100
D/OpenGLRenderer: ProgramCache.generateProgram: 103084458052
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: [socket][0] connection /192.168.43.76:80;LocalPort=-1(0)

              [ 02-07 22:40:39.251 29396:29665 D/         ]
              [Posix_connect Debug]Process com.example.access.test123 :80 
I/System.out: [socket][/192.168.43.1:49348] connected
I/System.out: [OkHttp] sendRequest>>
I/System.out: [OkHttp] sendRequest<<
D/Error2: java.net.ProtocolException: Unexpected status line: Test_Sucessfull
D/WindowClient: Add to mViews: android.widget.LinearLayout{3957537 V.E...... ......I. 0,0-0,0}, this = android.view.WindowManagerGlobal@d5cc9ee
D/OpenGLRenderer: CanvasContext() 0x7c56092d40
D/ViewRootImpl[Toast]: hardware acceleration is enabled, this = ViewRoot{f7a400d Toast,ident = 1}
D/Surface: Surface::allocateBuffers(this=0x7c58339e00)
D/OpenGLRenderer: CanvasContext() 0x7c56092d40 initialize window=0x7c58339e00, title=Toast
D/Surface: Surface::connect(this=0x7c58339e00,api=1)
W/libEGL: [ANDROID_RECORDABLE] format: 1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000
D/OpenGLRenderer: ProgramCache.generateProgram: 1
D/Surface: Surface::disconnect(this=0x7c58339e00,api=1)
D/Surface: Surface::disconnect(this=0x7c58339e00,api=1)
D/WindowClient: Remove from mViews: android.widget.LinearLayout{3957537 V.E...... ......ID 0,0-156,140}, this = android.view.WindowManagerGlobal@d5cc9ee
I/art: Do partial code cache collection, code=28KB, data=28KB
I/art: After code cache collection, code=27KB, data=28KB
I/art: Increasing code cache capacity to 128KB

注意:在D / Error2:java.net.ProtocolException:意外的状态行:Test_Sucessfull

收到字符串,但上面有错误。

结果:
IDE监视器显示从客户端发送的数据,即app IDE monitor displaying data sent from client i.e app

1 个答案:

答案 0 :(得分:0)

终于找到了解决方案,错误是从ESP端发送的响应数据包的语法

所以刚刚更换了

client.print( “Test_Successfull”);

client.print(“HTTP / 1.1 200 OK \ r \ nConnection:Closed \ r \ n \ r \ nTest_Successful”);