{"id":6200,"date":"2014-04-13T22:39:07","date_gmt":"2014-04-13T22:39:07","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/04\/13\/400-error-with-json-and-http-post-collection-of-common-programming-errors\/"},"modified":"2014-04-13T22:39:07","modified_gmt":"2014-04-13T22:39:07","slug":"400-error-with-json-and-http-post-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/04\/13\/400-error-with-json-and-http-post-collection-of-common-programming-errors\/","title":{"rendered":"400 Error with JSON and HTTP POST-Collection of common programming errors"},"content":{"rendered":"<p>Im trying to send an JSONObject over HTTPPost, however now Im receiving a 400 error.<\/p>\n<p>I&#8217;ve been going through with the server coder, and making smaller and more concise calls with a less complicated JSON object, however I still receive the same 400 error.<\/p>\n<p>How do I go about fixing it?<\/p>\n<pre><code>import java.io.IOException;\nimport java.io.UnsupportedEncodingException;\n\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.ClientProtocolException;\nimport org.apache.http.client.HttpClient;\nimport org.apache.http.client.methods.HttpPost;\nimport org.apache.http.entity.ByteArrayEntity;\nimport org.apache.http.entity.StringEntity;\nimport org.apache.http.impl.client.DefaultHttpClient;\nimport org.apache.http.message.BasicHeader;\nimport org.apache.http.params.BasicHttpParams;\nimport org.apache.http.params.HttpConnectionParams;\nimport org.apache.http.params.HttpParams;\nimport org.apache.http.protocol.HTTP;\nimport org.apache.http.util.EntityUtils;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport android.app.Activity;\nimport android.app.ProgressDialog;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.Menu;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class LoginScreen extends Activity {\n\n    private Button loginButton;\n    private TextView resultText;\n    private EditText usernameText;\n    private EditText passwordText;\n    private EditText switchChoice;\n    private EditText installText;\n    private int i;\n    private String accessURL = \"URL\";\n    private String accessNEW = \"\";\n    public final String CONSUMER_KEY = \"KEY\";\n    public final String CONSUMER_SECRET = \"SECRET\";\n\n    @Override\n    public void onCreate(Bundle savedInstanceState) {\n        \/\/ Create the screen + pull back the saved instance state\n        super.onCreate(savedInstanceState);\n        setContentView(R.layout.login_screen);\n\n        \/\/ initialize the buttons and text view for usability in the later codes\n        loginButton = (Button) findViewById(R.id.btn_login);\n        resultText = (TextView) findViewById(R.id.lbl_result);\n        usernameText = (EditText) findViewById(R.id.txt_username);\n        passwordText = (EditText) findViewById(R.id.txt_password);\n        installText = (EditText) findViewById(R.id.txt_install);\n        switchChoice = (EditText) findViewById(R.id.txt_switch);\n\n\n\n        \/\/ create the onclick listener for the login button to start the code to\n        \/\/ login\n        loginButton.setOnClickListener(new View.OnClickListener() {\n            public void onClick(View v) {\n                try {\n                    \/\/ pull data from EditText Boxes and create the JSON object\n                    \/\/ to send information HTTP\n                    String text = switchChoice.getText().toString();\n                    i = Integer.parseInt(text);\n                    JSONObject jOb = toJSON();\n                    Log.d(\"JSONObjectCreation\", jOb.toString());\n                    \/\/ method to go through\n                    processURL(jOb);\n                } catch (JSONException e) {\n                    e.printStackTrace();\n                }\n            }\n        });\n    }\n\n    @Override\n    public boolean onCreateOptionsMenu(Menu menu) {\n        getMenuInflater().inflate(R.menu.login_screen, menu);\n        return true;\n    }\n\n    public JSONObject toJSON() throws JSONException {\n        JSONObject credentials = new JSONObject();\n        try {\n            credentials.put(\"ConsumerSecret\", CONSUMER_SECRET);\n            credentials.put(\"ConsumerKey\", CONSUMER_KEY);\n            credentials.put(\"Password\", \"Sh0wT1me\");\n            credentials.put(\"Username\", \"sjones\");\n\n        } finally {\n        }\n        return credentials;\n    }\n\n    \/*\n     * Subclass that executes the connection and authentication to the server\n     * using HTTPPost - Uses AsyncTask to execute the network connection on a\n     * different thread\n     * \n     * PARAMS: JSONObject -&gt; input\n     *\/\n    private class PostTask extends AsyncTask {\n        \/\/ Dialog box to let user know that it is processing\n        private ProgressDialog Dialog = new ProgressDialog(LoginScreen.this);\n\n        \/\/ Before the execution of the background task, this is executed in the\n        \/\/ main thread\n        @Override\n        protected void onPreExecute() {\n            Dialog.setMessage(\"Logging In...\");\n\n            \/\/ forces the dialog to show in the main thread\n            Dialog.show();\n        }\n\n        \/\/ done in background thread, so that the main thread is not jammed up\n        \/\/ preventing user interface usage\n        @Override\n        protected String doInBackground(JSONObject... jObj) {\n            int TIMEOUT_MILLISEC = 10000; \/\/ create timeout time of 10 seconds\n            HttpParams httpParams = new BasicHttpParams();\n            HttpConnectionParams.setConnectionTimeout(httpParams,\n                    TIMEOUT_MILLISEC);\n            HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);\n\n            \/\/ create a new httpClient with the httpParams of timeout time\n            HttpClient client = new DefaultHttpClient(httpParams);\n            String responseBody = null;\n            try {\n\n                HttpPost request = new HttpPost(accessURL); \n\n                switch (i) {\n                case 1:\n                    request.setEntity(new ByteArrayEntity(jObj.toString().getBytes(\"UTF8\")));\n                    Log.d(\"request_entity\", request.getEntity().getContent().toString());\n                case 2:\n                     StringEntity params =new StringEntity(\"{credentials\"+jObj.toString()+\"}\");\n                        Log.i(\"String_Entity\", params.toString());\n\n                     request.addHeader(\"content-type\", \"application\/json; charset=utf-8\");\n                     request.setEntity(params);\n                case 3:\n                    StringEntity se = new StringEntity(\"{credentials\" + jObj.toString()+\"}\");  \n                    Log.i(\"String_Entity\", se.toString());\n                    se.setContentEncoding(\"UTF-8\");\n                    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, \"application\/json\"));\n                    request.setEntity(se);\n                case 4:\n\n                }\n\n                HttpResponse response = client.execute(request);\n                int status = response.getStatusLine().getStatusCode();\n                \/*\n                  switch (status) {\n                    case 200:\n\n                    HttpEntity entity = response.getEntity();\n                    if (entity != null) {\n                         responseBody = EntityUtils.toString(entity);\n                    }\n                    break;\n                case 500:\n                    responseBody = \"500\" + response.getStatusLine().getReasonPhrase();\n                    break;\n                }\n                *\/\n                String statusS = Integer.toString(status);\n                Log.d(\"request_status\", statusS);\n                return statusS + \" \" +response.getStatusLine().getReasonPhrase();\n                \/\/return responseBody;\n            } catch (UnsupportedEncodingException e) {\n                \/\/ TODO Auto-generated catch block\n                e.printStackTrace();\n            } catch (ClientProtocolException e) {\n                \/\/ TODO Auto-generated catch block\n                e.printStackTrace();\n            } catch (IOException e) {\n                \/\/ TODO Auto-generated catch block\n                Log.e(\"log_tag\", \"Error in http connection \" + e.toString());\n                e.printStackTrace();\n            }\n            return null;\n        }\n\n        @Override\n        protected void onPostExecute(String result) {\n            resultText.setText(result);\n            Dialog.dismiss();\n            Toast.makeText(getApplicationContext(), \"Value updated\",\n                    Toast.LENGTH_SHORT).show();\n        }\n    }\n\n    public void processURL(JSONObject thing) {\n        \/\/ execute connection on new thread\n        new PostTask().execute(thing);\n    }\n\n}\n<\/code><\/pre>\n<p>EDIT: The switch part for setting the entity is there because I wasnt sure if the error is from the manner in which I was setting the entity, so after research, I created a switch to let me go through the different methods that the JSONObject can be encoded to the entity.<\/p>\n<p>EDIT: This came up in my logcat today:<\/p>\n<pre><code>07-19 11:13:27.812: W\/ThrottleService(91): unable to find stats for iface rmnet0\n07-19 11:15:18.862: A\/NetworkStats(91): problem reading network stats\n07-19 11:15:18.862: A\/NetworkStats(91): java.lang.IllegalStateException: problem parsing line: null\n07-19 11:15:18.862: A\/NetworkStats(91):     at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:313)\n07-19 11:15:18.862: A\/NetworkStats(91):     at com.android.server.NetworkManagementService.getNetworkStatsUidDetail(NetworkManagementService.java:1271)\n07-19 11:15:18.862: A\/NetworkStats(91):     at com.android.server.net.NetworkStatsService.performPollLocked(NetworkStatsService.java:810)\n07-19 11:15:18.862: A\/NetworkStats(91):     at com.android.server.net.NetworkStatsService.performPoll(NetworkStatsService.java:771)\n07-19 11:15:18.862: A\/NetworkStats(91):     at com.android.server.net.NetworkStatsService.access$100(NetworkStatsService.java:128)\n07-19 11:15:18.862: A\/NetworkStats(91):     at com.android.server.net.NetworkStatsService$3.onReceive(NetworkStatsService.java:610)\n07-19 11:15:18.862: A\/NetworkStats(91):     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)\n07-19 11:15:18.862: A\/NetworkStats(91):     at android.os.Handler.handleCallback(Handler.java:605)\n07-19 11:15:18.862: A\/NetworkStats(91):     at android.os.Handler.dispatchMessage(Handler.java:92)\n07-19 11:15:18.862: A\/NetworkStats(91):     at android.os.Looper.loop(Looper.java:137)\n07-19 11:15:18.862: A\/NetworkStats(91):     at android.os.HandlerThread.run(HandlerThread.java:60)\n07-19 11:15:18.862: A\/NetworkStats(91): Caused by: java.io.FileNotFoundException: \/proc\/net\/xt_qtaguid\/stats: open failed: ENOENT (No such file or directory)\n07-19 11:15:18.862: A\/NetworkStats(91):     at libcore.io.IoBridge.open(IoBridge.java:406)\n07-19 11:15:18.862: A\/NetworkStats(91):     at java.io.FileInputStream.(FileInputStream.java:78)\n07-19 11:15:18.862: A\/NetworkStats(91):     at java.io.FileReader.(FileReader.java:42)\n07-19 11:15:18.862: A\/NetworkStats(91):     at com.android.internal.net.NetworkStatsFactory.readNetworkStatsDetail(NetworkStatsFactory.java:272)\n07-19 11:15:18.862: A\/NetworkStats(91):     ... 10 more\n07-19 11:15:18.862: A\/NetworkStats(91): Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)\n07-19 11:15:18.862: A\/NetworkStats(91):     at libcore.io.Posix.open(Native Method)\n07-19 11:15:18.862: A\/NetworkStats(91):     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:98)\n07-19 11:15:18.862: A\/NetworkStats(91):     at libcore.io.IoBridge.open(IoBridge.java:390)\n07-19 11:15:18.862: A\/NetworkStats(91):     ... 13 more\n: E\/(): Device disconnected\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Im trying to send an JSONObject over HTTPPost, however now Im receiving a 400 error. I&#8217;ve been going through with the server coder, and making smaller and more concise calls with a less complicated JSON object, however I still receive the same 400 error. How do I go about fixing it? import java.io.IOException; import java.io.UnsupportedEncodingException; [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-6200","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/6200","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=6200"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/6200\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=6200"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=6200"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=6200"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}