2017-11-30 10 views
0

私はAndroidをNode.jsに接続しようとしていますが、私はlocalhostにポート3000でサーバを稼働させていますが、POSTメソッドを使ってPOSTメソッドからデータを試してみると完全に動作しますが、クラスHttpUrlConnectionこれが結果です。¿AndroidをNode.jsに接続するには?

Result in the server

これはNode.jsの

router.post('/', (req, res)=>{ 
    console.log(req.query); 
    res.send({ 
    mensaje: 'I am from usuario routes' 
    }); 
}); 

からteのコードであり、これはあなたがサーバーに接続する前にデータを書き込む必要がありますアンドロイド

URL obj = new URL("http://192.168.1.107:3000/"); 
JSONObject jsonObject = new JSONObject(); 
jsonObject.put("image", "imagen"); 
String data = jsonObject.toString(); 
HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
con.setDoOutput(true); 
//con.setDoInput(true); 
con.setRequestMethod("POST"); 
con.setConnectTimeout(5000); 
con.setFixedLengthStreamingMode(data.getBytes().length); 
con.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 
con.connect(); 

OutputStream out = new BufferedOutputStream(con.getOutputStream()); 
BufferedWriter wrt = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); 
wrt.append(data); 
wrt.flush(); 

wrt.close(); 
out.close(); 
con.disconnect(); 
+0

'con.setDoInput(true)'を試しましたか? – Gianlu

+0

はい、問題は、サーバーは何も受信せず、要求だけを受信し、データは受信しないということです。 –

答えて

0

Androidでのリクエストは完璧ですが、ノードiではミドルウェアを使用してボディを変換していませんでした。ボディ解析モジュールを使用していました。

0

からです:

URL obj = new URL("http://192.168.1.107:3000/"); 

JSONObject jsonObject = new JSONObject(); 
jsonObject.put("image", "imagen"); 
String data = jsonObject.toString(); 

HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
con.setDoOutput(true); 
con.setDoInput(true); 
con.setRequestMethod("POST"); 
con.setConnectTimeout(5000); 
con.setFixedLengthStreamingMode(data.getBytes().length); 
con.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 

OutputStream os = con.getOutputStream(); 
BufferedWriter wrt = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
wrt.append(data); 
wrt.flush(); 
wrt.close(); 
os.close(); 

con.connect(); 
+0

動作しません:(....私はデバッグをしています。次の行で 'wrt.flush()'を実行しても 'wrt'はまだデータを持っています...私はデータがないと思いますサーバでは空の 'req.query'が来るのでリクエストはyesです。 –

+0

@DavidSotelo私はBufferedWriterを単純化しました。今すぐ試してみてください。 – Gianlu

関連する問題