如何将JSON数据发送到android中的服务器?

时间:2017-06-20 12:58:52

标签: android json

由于所有旧方法已被弃用,例如http post,response,http client,string entity等,我想知道如何在2017年将json数据发布到android中的服务器。我的应用程序应该注册或发送使用POST方法向服务器发送JSON数据(如电子邮件,联系号码和密码),然后服务器将提供JSON响应,如状态,消息和名为data的数组。数据是仅包含2个对象(即令牌和电子邮件)的数组。请帮忙。

3 个答案:

答案 0 :(得分:1)

我认为您需要尝试使用Loopj库来发送Json数据 you can try this link 并且很容易理解 You can try another link

try{

        AsyncHttpClient client = new AsyncHttpClient();
        JSONObject obj = new JSONObject();

        obj.put("email",email);
        obj.put("contact_number",contact_number);
        obj.put("password",password);
        entity = new StringEntity(obj.toString());

        client.post(getApplicationContext(), "Your_URL", entity, "application/json", new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("LoginActivity","Failed");
                Log.d("LoginActivity","body " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("LoginActivity","data " + responseString);
                try {
                    JSONObject respObj = new JSONObject(responseString);
                    String data = respObj.toString();
                    Log.d("LoginActivity","Data : " + data);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }catch (Exception ex){
        Log.d("LoginActivity","Getting Exception "+ex.toString());
    }

答案 1 :(得分:0)

试试这个

    private void registerUser(){
    final String username = editTextUsername.getText().toString().trim();
    final String password = editTextPassword.getText().toString().trim();
    final String email = editTextEmail.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            params.put(KEY_EMAIL, email);
            return params;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

答案 2 :(得分:0)

使用volley执行该操作,请按照链接检查示例。volley example

  

创建RequestQueue类的对象。

 RequestQueue queue = Volley.newRequestQueue(this);
  

使用响应和错误侦听器创建StringRequest。

StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        mPostCommentResponse.requestCompleted();
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mPostCommentResponse.requestEndedWithError(error);
    }
}){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<String, String>();
        params.put("user",userAccount.getUsername());
        params.put("pass",userAccount.getPassword());
        params.put("comment", Uri.encode(comment));
        params.put("comment_post_ID",String.valueOf(postId));
        params.put("blogId",String.valueOf(blogId));

        return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> params = new HashMap<String, String>();
        params.put("Content-Type","application/x-www-form-urlencoded");
        return params;
    }
};
  
      
  • 将您的请求添加到RequestQueue。
  •   
 queue.add(jsObjRequest);