android客户端无法发布json

android客户端无法发布json,android,json,http,parsing,post,Android,Json,Http,Parsing,Post,我正在编写简单的用户注册表格。我有3个editview字段用于名称、密码和电子邮件。我的服务器是restful服务器 我的问题是我无法发送POST变量(用户输入)。 以JSON的形式显示。我已经为此工作了3天了,我几乎尝试了stackoverflow和google的所有功能。请帮忙 我的服务器接受此表单中的数据 "{\"fname\":\"xyz\",\"email\":\"xyz@yahoo.com\",\"password\":\"asd\"}" 我的服务器以这种形式获取它,这给了我

我正在编写简单的用户注册表格。我有3个editview字段用于名称、密码和电子邮件。我的服务器是restful服务器

我的问题是我无法发送POST变量(用户输入)。 以JSON的形式显示。我已经为此工作了3天了,我几乎尝试了stackoverflow和google的所有功能。请帮忙

我的服务器接受此表单中的数据

   "{\"fname\":\"xyz\",\"email\":\"xyz@yahoo.com\",\"password\":\"asd\"}"
我的服务器以这种形式获取它,这给了我数据库错误和JSON异常错误

        email=xyz@yahoo.com&password=asd&fname=xyz
RegisterActivity.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();
        }

    }
}
package com.login.recscores;
导入java.io.BufferedReader;
导入java.io.DataOutputStream;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.urlcoder;
导入java.util.ArrayList;
导入java.util.List;
导入org.apache.http.NameValuePair;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
公共类注册活动扩展活动{
//进度对话框
私人对话;
编辑文本博物馆名称;
编辑文本mPassword;
编辑文本文件;
按钮mSignUp;
文本视图温度;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
//编辑文本
mUsername=(EditText)findViewById(R.id.name);
mEmail=(EditText)findViewById(R.id.email);
mPassword=(EditText)findViewById(R.id.password);
temp=(TextView)findViewById(R.id.temp);;
//创建按钮
按钮mSignUp=(按钮)findViewById(R.id.sign\u up\u按钮);
//按钮点击事件
mSignUp.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图){
//在后台线程中创建新产品
新建CreateNewUser().execute();
}
});
}
/**
*创建新用户的后台异步任务
* */
类CreateNewUser扩展异步任务{
//在启动后台线程显示进度对话框之前
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(RegisterActivity.this);
pDialog.setMessage(“注册…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
//创建用户
受保护的字符串doInBackground(字符串…args){
字符串fname=mUsername.getText().toString();
字符串email=mEmail.getText().toString();
字符串密码=mPassword.getText().toString();
试一试{
字符串urlParameters=“fname=”
+urlcoder.encode(fname,“UTF-8”)+“&电子邮件=”
+urlcoder.encode(电子邮件,“UTF-8”)+“&密码=”
+urlcoder.encode(密码为“UTF-8”);
}捕获(不支持的编码异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
sendPostData(“http://10.0.2.2/api/register“,参数);
}
公共静态字符串sendPostData(字符串targetURL、字符串urlParameters){
网址;
HttpURLConnection=null;
试一试{
//创建连接
url=新url(targetURL);
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod(“POST”);
connection.setRequestProperty(“内容类型”,
“application/x-www-form-urlencoded”);
connection.setRequestProperty(“内容长度”,
“”+Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty(“内容语言”、“en-US”);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(真);
//发送请求
DataOutputStream wr=新的DataOutputStream(
connection.getOutputStream());
writeBytes(URL参数);
wr.flush();
wr.close();
//得到回应
InputStream is=connection.getInputStream();
BufferedReader rd=新的BufferedReader(新的InputStreamReader(is));
弦线;
StringBuffer响应=新的StringBuffer();
而((line=rd.readLine())!=null){
响应。追加(行);
append('\r');
}
rd.close();
返回response.toString();
}捕获(例外e){
e、 printStackTrace();
返回null;
}最后{
if(连接!=null){
连接断开();
}
}
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//完成后关闭对话框
pDialog.disclose();
}
}
}
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;
publicJSONObject生成HttpRequest
    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();
            }
        }
    }