【问题标题】:android client unable to POST jsonandroid客户端无法POST json
【发布时间】:2013-01-27 11:34:42
【问题描述】:

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

我的问题是我无法发送 POST 变量(用户输入。 的editview)以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();
        }

    }
}

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;

}

【问题讨论】:

    标签: android json http parsing post


    【解决方案1】:

    下面的代码对我有用。

        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 方法从服务器返回(字符串)回调响应,您可以将其用于进一步操作。
    编码快乐!!

    【讨论】:

    • 非常感谢您的回答。我在我的 RegisterActivity.java 中实现了您的代码。我已经粘贴了上面的完整代码。我收到两个错误 ....1) 描述资源路径位置类型方法 sendPostData 不能声明为静态;静态方法只能在静态或顶级类型RegisterActivity.java中声明............2)描述资源路径位置类型urlParameters不能解析为变量RegisterActivity.java
    • 我可以使用 curl 做同样的操作,没有问题 curl -v -H "Content-Type:application/json" -X POST localhost/api/register -d "{\"email \":\"xyz@yahoo.com\",\"密码\":\"asd\",\"fname\":\"xyz\"}"
    • 感谢您为我指明正确的方向。我需要将 json 对象传递给 URL。这解决了我的问题...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2016-03-16
    • 1970-01-01
    相关资源
    最近更新 更多