Android使用Json-404向节点发送请求

时间:2017-12-14 12:13:50

标签: android json node.js

我在android中有一个客户端,我试图发布到nodejs服务器。 我一直得到404。 这是我的客户方:

package com.example.shanijoffe.hungry_monkey;

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

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.squareup.okhttp.OkHttpClient;
import com.stormpath.sdk.Stormpath;
import com.stormpath.sdk.StormpathConfiguration;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;

import static com.loopj.android.http.AsyncHttpClient.log;

public class MainActivity extends AppCompatActivity {


    EditText user_name_edit;
    EditText password_edit;
    Button loginButton;
    String user;
    String user_pass;
    static final int CODE_REQ=1;
    private static final String TAG = "MyActivity";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        user_name_edit=(EditText)findViewById(R.id.txt_usrname);
        password_edit=(EditText)findViewById(R.id.txt_password);
        loginButton=(Button)findViewById(R.id.btn_login);

        Log.i(TAG,"before connection");


    }
        public void OnClick(final View view) throws IOException {
            view.setEnabled( false );
            user = user_name_edit.getText().toString();
            user_pass = password_edit.getText().toString();
            log.i( "hi", "sup" );
            new SendPostRequest().execute();

            // log.i( "our s is :", ss.toString() );
            int exist_user = 0;
            exist_user = 1;
            if (exist_user == 1) {
                Intent i = new Intent( this, ExistUserHomePage.class );
                String s = "משתשמש קיים  ";
                i.putExtra( "myString", s );
                startActivityForResult( i, CODE_REQ );
            }
        }

    public class SendPostRequest extends AsyncTask<String, Void, String> {
        protected void onPreExecute(){}
        protected String doInBackground(String... arg0) {
            try {
                log.i("in doInBackground ","1");
                URL url = new URL("https://rocky-thicket-82184.herokuapp.com/api/v1/auth"); // here is your URL path
                JSONObject postDataParams = new JSONObject();
                postDataParams.put("name",user);
                postDataParams.put("pass",user_pass);
                Log.e("params",postDataParams.toString());
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                int responseCode=conn.getResponseCode();
                log.i("responseCode is:", String.valueOf( responseCode ) );
                conn.setReadTimeout(15000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));
                writer.flush();
                writer.close();
                os.close();
                log.i("kokoko","koko");

                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    BufferedReader in=new BufferedReader(new
                            InputStreamReader(
                            conn.getInputStream()));
                    StringBuffer sb = new StringBuffer("");
                    String line="";
                    while((line = in.readLine()) != null) {
                        sb.append(line);
                        break;
                    }
                    in.close();
                    return sb.toString();
                }
                else {
                    return new String("false : "+responseCode);
                }
            }
            catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }
        }
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getApplicationContext(), result,
                    Toast.LENGTH_LONG).show();
        }
    }
    public String getPostDataString(JSONObject params) throws Exception {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        Iterator<String> itr = params.keys();
        while(itr.hasNext()){
            String key= itr.next();
            Object value = params.get(key);
            if (first)
                first = false;
            else
                result.append("&");
            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));
        }
        return result.toString();
    }
}

这是我的服务器端-Nodejs:

routes.js:
'use strict';

const auth = require('basic-auth');
const jwt = require('jsonwebtoken');

const register = require('./functions/register');
const login = require('./functions/login');
const profile = require('./functions/profile');
const password = require('./functions/password');
const config = require('./config/config.json');
//var bodyParser = require('body-parser');
module.exports = router => {

    router.get('/', (req, res) =>{

        res.end('Welcome to Learn2Crack !')});

    router.post('/auth', (req, res) => {
        var temp3=req.body;
        var temp=req.body.name;
        var temp2=req.body.pass;
        console.log(temp3);
        console.log(temp);
        console.log(temp2);
            //.catch(err => res.status(err.status).json({ message: err.message }));
        res.end('im a dush '+temp2);
    });

server.js:

'use strict';

const express    = require('express');        
const app        = express();                
const bodyParser = require('body-parser');
const logger       = require('morgan');
const router       = express.Router();
const port     = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(logger('dev'));

require('./routes')(router);
app.use('/api/v1', router);

app.listen(port);

console.log(App Runs on ${port});

现在,我正在使用邮递员来测试我的帖子请求,一切都很好。但是从android studio我一直得到404。 我错过了什么吗? 有人可以在这里发光吗??

这是来自服务器端的日志:

server logs

这里有一些logcat打印:

2-14 11:55:44.847 1306-1306/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
12-14 11:55:47.348 5133-5133/com.example.shanijoffe.hungry_monkey W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
12-14 11:55:47.350 1371-1424/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 1269717 , only wrote 1269360
12-14 11:55:49.849 5133-5133/com.example.shanijoffe.hungry_monkey I/hi: sup
12-14 11:55:49.849 1686-1700/system_process I/ActivityManager: START u0 {cmp=com.example.shanijoffe.hungry_monkey/.ExistUserHomePage (has extras)} from uid 10088 on display 0
12-14 11:55:49.849 5133-5149/com.example.shanijoffe.hungry_monkey I/in doInBackground: 1
12-14 11:55:49.850 5133-5149/com.example.shanijoffe.hungry_monkey E/params: {"name":"ss","pass":"sws"}
12-14 11:55:49.853 5133-5149/com.example.shanijoffe.hungry_monkey D/NetworkSecurityConfig: No Network Security Config specified, using platform default
12-14 11:55:50.171 5133-5148/com.example.shanijoffe.hungry_monkey D/EGL_emulation: eglMakeCurrent: 0x9dd85240: ver 2 0 (tinfo 0x9dd83240)
12-14 11:55:50.602 5133-5133/com.example.shanijoffe.hungry_monkey W/IInputConnectionWrapper: finishComposingText on inactive InputConnection
12-14 11:55:50.621 5133-5149/com.example.shanijoffe.hungry_monkey I/responseCode is:: 404
12-14 11:55:50.677 1686-1709/system_process I/ActivityManager: Displayed com.example.shanijoffe.hungry_monkey/.ExistUserHomePage: +774ms
12-14 11:55:51.135 5133-5148/com.example.shanijoffe.hungry_monkey D/EGL_emulation: eglMakeCurrent: 0x9dd85240: ver 2 0 (tinfo 0x9dd83240)
12-14 11:55:51.321 1306-1306/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
12-14 11:55:53.036 1371-1425/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 1813461 , only wrote 1542240
12-14 11:55:54.201 1686-1686/system_process W/WindowManager: Attempted to remove non-existing token: android.os.Binder@b393592
12-14 11:55:54.201 5133-5148/com.example.shanijoffe.hungry_monkey D/EGL_emulation: eglMakeCurrent: 0x9dd85240: ver 2 0 (tinfo 0x9dd83240)
12-14 11:56:14.336 2282-2282/com.google.android.googlequicksearchbox:search I/GrammarCompilationSvcCt: #startService for null, APP_NAMES.
12-14 11:56:14.349 2282-5160/com.google.android.googlequicksearchbox:search I/ContextCompilationHandl: Compiling grammar for: en-US, type=APP_NAMES
12-14 11:56:14.352 2282-5160/com.google.android.googlequicksearchbox:search I/ContextCompilationHandl: No grammar compilation resources for VOICE_ACTIONS_COMPILER, aborting. 
12-14 11:56:42.858 2282-2282/com.google.android.googlequicksearchbox:search I/GrammarCompilationSvcCt: #startService for null, APP_NAMES.
12-14 11:56:42.866 2282-5161/com.google.android.googlequicksearchbox:search I/ContextCompilationHandl: Compiling grammar for: en-US, type=APP_NAMES
12-14 11:56:42.870 2282-5161/com.google.android.googlequicksearchbox:search I/ContextCompilationHandl: No grammar compilation resources for VOICE_ACTIONS_COMPILER, aborting. 
12-14 11:57:06.904 1377-3736/? D/WVCdm: Instantiating CDM.
12-14 11:57:06.905 1377-3736/? I/WVCdm: CdmEngine::OpenSession
12-14 11:57:06.905 1377-3736/? I/WVCdm: Level3 Library 4464 Sep 10 2016 21:49:53
12-14 11:57:06.906 1377-3736/? W/WVCdm: Could not load liboemcrypto.so. Falling back to L3.  dlopen failed: library "liboemcrypto.so" not found
12-14 11:57:06.911 1377-3736/? I/WVCdm: CdmEngine::QueryKeyControlInfo
12-14 11:57:06.911 1377-3736/? I/WVCdm: CdmEngine::GenerateKeyRequest

1 个答案:

答案 0 :(得分:0)

HttpURLConnection.getResponseCode隐式地将调用其父类URLConnection的{​​{1}}方法,该方法将使用默认的connect方法启动并发出HTTP请求。由于您在配置GET实例以进行POST之前进行此调用,因此连接会连接并获取404,因为为服务器上的HttpURLConnection路径指定了get处理程序。 / p>