0

我正在制作简单的用户注册表单。我有 3 个用于名称、密码和电子邮件的编辑视图字段。我的服务器是一个安静的服务器。

我的问题是我无法以 JSON 的形式发送 POST 变量(用户输入。editview)。我现在已经为此工作了 3 天,我已经尝试了几乎所有来自 stackoverflow 和谷歌的东西。请帮忙

我的服务器接受这种形式的数据

   "{\"fname\":\"xyz\",\"email\":\"xyz@yahoo.com\",\"password\":\"asd\"}"

我的服务器以这种形式获取它,这给了我数据库错误,因此出现 JSON 异常错误。

        email=xyz@yahoo.com&password=asd&fname=xyz

注册活动.java

package com.login.recscores;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RegisterActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;



    EditText mUsername;
    EditText mPassword;
    EditText mEmail;
    Button mSignUp ;
    TextView temp;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);



        // Edit Text

        mUsername = (EditText)findViewById(R.id.name);
        mEmail = (EditText)findViewById(R.id.email);
        mPassword = (EditText)findViewById(R.id.password);
        temp=(TextView)findViewById(R.id.temp);;

        // Create button
        Button mSignUp = (Button) findViewById(R.id.sign_up_button);

        // button click event
        mSignUp.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewUser().execute();
            }
        });
    }

    /**
     * Background Async Task to Create new user
     * */


    class CreateNewUser extends AsyncTask<String, String, String> {


    //   Before starting background thread Show Progress Dialog

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(RegisterActivity.this);
            pDialog.setMessage("Signing Up..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }


         // Creating User

        protected String doInBackground(String... args) {
            String fname = mUsername.getText().toString();
            String email = mEmail.getText().toString();
            String password = mPassword.getText().toString();
            try {
                String urlParameters = "fname="
                            + URLEncoder.encode(fname, "UTF-8") + "&email="
                            + URLEncoder.encode(email, "UTF-8")+ "&password="
                            + URLEncoder.encode(password, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            sendPostData("http://10.0.2.2/api/register", urlParameters);
        }


        public static String sendPostData(String targetURL, String urlParameters) {
                URL url;
                HttpURLConnection connection = null;
                try {
                    // Create connection
                    url = new URL(targetURL);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-Type",
                            "application/x-www-form-urlencoded");

                    connection.setRequestProperty("Content-Length",
                            "" + Integer.toString(urlParameters.getBytes().length));
                    connection.setRequestProperty("Content-Language", "en-US");

                    connection.setUseCaches(false);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);

                    // Send request
                    DataOutputStream wr = new DataOutputStream(
                            connection.getOutputStream());
                    wr.writeBytes(urlParameters);
                    wr.flush();
                    wr.close();

                    // Get Response
                    InputStream is = connection.getInputStream();
                    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                    String line;
                    StringBuffer response = new StringBuffer();
                    while ((line = rd.readLine()) != null) {
                        response.append(line);
                        response.append('\r');
                    }
                    rd.close();
                    return response.toString();
                } catch (Exception e) {

                    e.printStackTrace();
                    return null;

                } finally {

                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }



        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}

JSON解析器是

    public JSONObject makeHttpRequest(String url, String method,
    List<NameValuePair> params) {

// Making HTTP request
try {

    // check for request method
    if(method == "POST"){
        // request method is POST
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    }else if(method == "GET"){
        // request method is GET
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    }           

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    is.close();
    json = sb.toString();
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}

4

1 回答 1

0

下面的代码对我有用。

    protected String doInBackground(String... args) {
    try {
        String urlParameters = "fname="
                    + URLEncoder.encode("firstnamestring", "UTF-8") + "&email="
                    + URLEncoder.encode("emailaddressstring", "UTF-8")+ "&password="
                    + URLEncoder.encode("passwordstring", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    sendPostData("http://webserviceurl.com", urlParameters);
}


public static String sendPostData(String targetURL, String urlParameters) {
        URL url;
        HttpURLConnection connection = null;
        try {
            // Create connection
            url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length",
                    "" + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            // Send request
            DataOutputStream wr = new DataOutputStream(
                    connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            // Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }
    }

请注意,sendPostData 方法从服务器返回(字符串)回调响应,您可以将其用于进一步操作。
快乐编码!

于 2013-01-27T11:46:31.897 回答