[Android]-POST Json with HttpUrlConnection

2019-05-30 06:47发布

I build a server side to my application when I send a requests to this server with python-script its work good, but with my app it doesn't work.

Server:

the server contains a database. when I send a JSON {"name":"your_name"} the server save in the DB the name.

App(Android):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonSend=(Button)findViewById(R.id.button_send);


    buttonSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AsyncTaskRunner postReq = new AsyncTaskRunner();
            postReq.execute("start");

        }
    });
}

private class AsyncTaskRunner extends AsyncTask<String,String,String>{
    @Override
    protected String doInBackground(String... params) {
        try {
            String url="my url";
            URL object=new URL(url);

            HttpURLConnection con = (HttpURLConnection) object.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            con.setRequestMethod("POST");

            JSONObject cred = new JSONObject();
            cred.put("name","my_name")

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


        }
        catch (Exception e){
            Log.v("ErrorAPP",e.toString());
        }
        return "";
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
    }
}

In the phone that i run this app I sniff data and i see that the app send a request to the server but the packet doesn't contains the json

1条回答
做自己的国王
2楼-- · 2019-05-30 07:04

I slove it!

change that:

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

to:

DataOutputStream localDataOutputStream = new DataOutputStream(con.getOutputStream());
            localDataOutputStream.writeBytes(cred.toString());
            localDataOutputStream.flush();
            localDataOutputStream.close();
查看更多
登录 后发表回答