如何使用HTTP POST将ANDROID应用程序中的JSON对象发布到Web服务器?

时间:2017-03-02 09:55:39

标签: android json web-services

  

我做了一个注册表单,它发送从注册函数中获取的数据并发布到url(实际上保存在另一个类中)   问题是json对象没有被发送到服务器。来自服务器的响应表明" {"设置":{"成功":" 0","消息":"请输入first_name字段的值""字段":[]},"数据":[]}"
  有人可以帮我理解我哪里出错了。   这是我的代码片段:

public void signup() throws JSONException {
    String firstname = edittext_fname.getText().toString();
    String lastname = editext_lname.getText().toString();
    String email = editext_email.getText().toString();
    String mobile = editext_mobile.getText().toString();
    String pass = editext_pass.getText().toString();
    String username = editext_user.getText().toString();
    String address = editext_add.getText().toString();
    String cityname = editText_city.getText().toString();
    String zipcode = editText_Zip.getText().toString();
    String city_id = editText_cityid.getText().toString();
    String birthdate = textView_birth.getText().toString();
    String statename = textView_state.getText().toString();
    String stateid = state_id;

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("first_name", firstname);
    jsonObject.put("last_name", lastname);
    jsonObject.put("birth_date", birthdate);
    jsonObject.put("email", email);
    jsonObject.put("user_name", username);
    jsonObject.put("password", pass);
    jsonObject.put("mobile_no", mobile);
    jsonObject.put("address", address);
    jsonObject.put("zip_code", zipcode);
    jsonObject.put("city_id", city_id);
    jsonObject.put("city", cityname);
    jsonObject.put("state_id", stateid);
    jsonObject.put("reference_name", "xxx");
    jsonObject.put("country_id", "223");
    jsonObject.put("refer_by", "others");
    jsonObject.put("user_role_type", "3");

    if (jsonObject.length() > 0) {
        new sendJsonData().execute(String.valueOf(jsonObject));
    }


}
  

设置HttpUrlConnection并附加json对象的异步类

private class sendJsonData extends AsyncTask<String, Void, String> {
    ProgressDialog progressDialog;
    String Jsonresponse = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(FirstScreenActivity.this);
        progressDialog.setMessage("please wait");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        String Jsondata = params[0];

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        try {

            URL url = new URL(WsUtils.BASE_URL+WsUtils.SIGNUP);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(10000);
            urlConnection.setRequestProperty("Accept","application/json");
            urlConnection.setRequestProperty("Content-Type","application/json");

            //Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
            //writer.write(Jsondata);
           // writer.close();

            DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream ());
            printout.writeBytes("PostData=" + Jsondata);
            printout.writeBytes(Jsondata);
            Log.e("json", Jsondata);

           // printout.flush ();
           // printout.close ();

            DataInputStream in = new DataInputStream(urlConnection.getInputStream());
            Jsonresponse = convertStreamToString(in);




            return Jsonresponse;


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        progressDialog.dismiss();
        Log.e("response", Jsonresponse);

    }


}
  

这只是为了获得字符串的输入(响应)并获得显示!

public String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

4 个答案:

答案 0 :(得分:2)

此处您可以看到如何使用 HttpURLConnection

发布数据
public class sendJsonData  extends AsyncTask<String, Void, String> {

    protected void onPreExecute(){}

    protected String doInBackground(String... arg0) {

      try {

          URL url = new URL(WsUtils.BASE_URL+WsUtils.SIGNUP); // here is your URL path

        JSONObject jsonObject = new JSONObject();
jsonObject.put("first_name", firstname);
jsonObject.put("last_name", lastname);
jsonObject.put("birth_date", birthdate);
jsonObject.put("email", email);
jsonObject.put("user_name", username);
jsonObject.put("password", pass);
jsonObject.put("mobile_no", mobile);
jsonObject.put("address", address);
jsonObject.put("zip_code", zipcode);
jsonObject.put("city_id", city_id);
jsonObject.put("city", cityname);
jsonObject.put("state_id", stateid);
jsonObject.put("reference_name", "xxx");
jsonObject.put("country_id", "223");
jsonObject.put("refer_by", "others");
jsonObject.put("user_role_type", "3");
        Log.e("params",postDataParams.toString());

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        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(jsonObject));

            writer.flush();
            writer.close();
            os.close();

            int responseCode=conn.getResponseCode();

            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) {
         progressDialog.dismiss();
         Log.e("response", result);
    }
}

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();
}

答案 1 :(得分:0)

使用名为ion:https://github.com/koush/ion的库。您所要做的就是在app build.gradle中添加依赖项,如下所示:

compile 'com.koushikdutta.ion:ion:2.+'

然后将json数据发送到您的服务器就像这样简单:

public void signup() throws JSONException {
        String firstname = edittext_fname.getText().toString();
        String lastname = editext_lname.getText().toString();
        String email = editext_email.getText().toString();
        String mobile = editext_mobile.getText().toString();
        String pass = editext_pass.getText().toString();
        String username = editext_user.getText().toString();
        String address = editext_add.getText().toString();
        String cityname = editText_city.getText().toString();
        String zipcode = editText_Zip.getText().toString();
        String city_id = editText_cityid.getText().toString();
        String birthdate = textView_birth.getText().toString();
        String statename = textView_state.getText().toString();
        String stateid = state_id;

        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("first_name", firstname);
        jsonObject.addProperty("last_name", lastname);
        jsonObject.addProperty("birth_date", birthdate);
        jsonObject.addProperty("email", email);
        jsonObject.addProperty("user_name", username);
        jsonObject.addProperty("password", pass);
        jsonObject.addProperty("mobile_no", mobile);
        jsonObject.addProperty("address", address);
        jsonObject.addProperty("zip_code", zipcode);
        jsonObject.addProperty("city_id", city_id);
        jsonObject.addProperty("city", cityname);
        jsonObject.addProperty("state_id", stateid);
        jsonObject.addProperty("reference_name", "xxx");
        jsonObject.addProperty("country_id", "223");
        jsonObject.addProperty("refer_by", "others");
        jsonObject.addProperty("user_role_type", "3");

        Ion.with(context)
                .load(WsUtils.BASE_URL+WsUtils.SIGNUP)
                .setJsonObjectBody(jsonObject)
                .asJsonObject()
                .setCallback(new FutureCallback<JsonObject>() {
                    @Override
                    public void onCompleted(Exception e, JsonObject result) {
                        if(e != null) {
                            //AN ERROR OCCURRED
                            return;
                        }

                        //REQUEST WAS SUCCESSFUL
                    }
                });


    }

答案 2 :(得分:0)

//创建连接的全局类

public class ConnectAsynchronously {

private static int requestCode;
private static String myMessage;

public static String connectAsynchronously(String uri) {
    String result ="";
    try {
        //Connect
        HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setRequestMethod("GET");

        urlConnection.connect();
        requestCode=urlConnection.getResponseCode();
        myMessage = urlConnection.getResponseMessage();
        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        bufferedReader.close();
        result = sb.toString();
    }  catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

public static String connectAsynchronously(String uri, JSONObject jobj) {
    String result ="";
    try {
        //Connect
        HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(jobj.toString());
        writer.close();
        outputStream.close();
        requestCode=urlConnection.getResponseCode();
        myMessage = urlConnection.getResponseMessage();

        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String line ;
        StringBuilder sb = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        bufferedReader.close();
        result = sb.toString();
    }  catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}



public static int getRequestCode(){

    return requestCode;
}

public static String getRequestMessage(){

    return myMessage;
}

}

//现在在您的主要活动发布数据中

//制作一个班级

 private class RegistrationTask extends AsyncTask<String, Void, String> {
    final JSONObject jsonObject;

    public RegistrationTask(JSONObject jsonObject) {
        this.jsonObject = jsonObject;
    }

    @Override
    protected String doInBackground(String... params) {
        return ConnectAsynchronously.connectAsynchronously(params[0],jsonObject);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        int requestCode =ConnectAsynchronously.getRequestCode();
        if(requestCode== HttpURLConnection.HTTP_OK){
            //sucess
        }else {
            Toast.makeText(getApplicationContext(),ConnectAsynchronously.getRequestMessage(),Toast.LENGTH_LONG).show();
        }

    }
}

//最后请求

 JSONObject jsonObject =new JSONObject();
    try {
        jsonObject.put("","");
       /* make ur Json Object like this*/
    } catch (JSONException e) {
        e.printStackTrace();
    }

    new RegistrationTask(jsonObject).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"YOUR_POST_URL");

答案 3 :(得分:0)

使用:

   OutputStream os = conn.getOutputStream();
   os.write(json.toString().getBytes("UTF-8"));
   os.close();

而不是:

DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream ());
printout.writeBytes("PostData=" + Jsondata);
printout.writeBytes(Jsondata);