Liy*_*iya 9 sockets android json
我无法在套接字连接中得到响应,我无法理解代码有什么问题.我能够使用ip地址和端口号建立套接字连接,并且它正在进入
if (nsocket.isConnected()) {}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用telnet时,我可以得到响应.但输入还有一些其他参数,如:
POST/setMap HTTP/1.1主机:192.168.1.1 Content-Type:application/json; charset = utf-8内容长度:1234
{"cmd":"request_get_file_list","验证":"CVS"}
我不知道如何在代码中包含内容类型,长度等连接属性.
这是代码:
public class WebService {
public static String devicelisting() {
Socket nsocket;
String response = null;
try {
nsocket = new Socket("192.168.1.1", 6666);
if (nsocket.isConnected()) {
JSONObject json = new JSONObject();
json.put("cmd", "request_get_file_list");
json.put("verification", "CVS");
Log.i("AsyncTask", "doInBackground: Creating socket");
// nsocket = new Socket();
OutputStreamWriter out = new OutputStreamWriter(nsocket.getOutputStream(), StandardCharsets.UTF_8);
out.write(json.toString());
Log.i("Webservice", "json.toString"+json.toString());
InputStream in = new BufferedInputStream(nsocket.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder stringbuilder = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
stringbuilder.append(line);
Log.i("line", "line.line"+line);
}
response = stringbuilder.toString();
Log.i("Response", response);
}
else{
Log.i("Response", "not connected");
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
Run Code Online (Sandbox Code Playgroud)
请帮我找到问题.我被严重困扰.请帮我解决问题
对于套接字驱动的事件,很难实现许多功能,但有一些(开源)库可以实现这样的任务。考虑使用Socket.io。
Properties headers = new Properties();
headers.setProperty("Content-Type","application/json"); // your headers
SocketIO socketIO = SocketIO(url, headers);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看SocketIO 文档
编辑
在给定的示例中,您应该使用HttpURLConnection,因为您从服务器获取响应,不需要实现套接字。只需使用 HttpURLConnectionGET获取POST或推送数据。
| 归档时间: |
|
| 查看次数: |
747 次 |
| 最近记录: |