如何使用HTTP Post将JSON对象从Android应用程序发布到Web服务器



我已经制作了一个注册表格,该表格将从注册功能获取并发布到URL(实际上保存在另一个类中) 问题在于,JSON对象未发送到服务器。服务器的回复指出" {"设置":{"成功":" 0","消息:"请输入第一个_name字段的值。"," fields":[]}," data":[]}"
有人可以帮我了解我出了什么问题吗? 这是我的代码片段:

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对象

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

在这里您可以看到如何使用 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();
}

使用此库,称为ion:https://github.com/koush/ion。您所要做的就是添加应用程序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
                    }
                });

    }

//进行连接的全局类

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");

使用:

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

相关内容

  • 没有找到相关文章

最新更新