abdfahim
abdfahim

Reputation: 2553

Passing JSONObject with Httppost

I am trying to pass JSONObject with Httppost but getting 406 Error (SC_NOT_ACCEPTABLE).

I have tried different solutions proposed in SO like adding header, using StringEntity, but nothing is working for me.

Can anybody please help me?

ASYNCTASK CLASS: doInBackground method:

String URL = "www.myURL.com/myfile.php";
    String key = "mykey";

    mylibmandbhandler db = new mylibmandbhandler(ImExActivity.this);
    JSONArray jason = db.exportDb(); // exportDb() returns JSONArray
    db.close();
    HttpParams httpParameters = new BasicHttpParams();
    int timeoutConnection = 10000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutConnection);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);
    HttpResponse response = null;
try {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("key", key);
    jsonObject.put("output", jason);
    StringEntity output = new StringEntity(jsonObject.toString());
    httppost.setEntity(output);
    httppost.addHeader("Accept", "application/json");
    httppost.addHeader("Content-type", "application/json");
    response = httpclient.execute(httppost);
    if(response.getStatusLine().getStatusCode()!=200){
        return " E511: "+response.getStatusLine().getStatusCode()+": "+response.getStatusLine().toString();
    }
    HttpEntity entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity);
    return responseBody;
    } catch (Exception e) {
    return "E509: Error in connection";
}

myfile.php

if(!isset($_POST['key'])){
    echo "Denied.";
    exit();
}else{
    echo $post['output'];
    exit();
}

LOGCAT: There is no error, but if I print responseBody, I get the following in logcat. However, there is no problem with the existence of the file, as if I send normal string (not JSON), everything works fine.

12-07 04:58:33.090: D/aaaa(1243):  E511: 406: HTTP/1.1 406 Not Acceptable
12-07 04:58:33.130: D/aaaa(1243): <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
12-07 04:58:33.130: D/aaaa(1243): <html><head>
12-07 04:58:33.130: D/aaaa(1243): <title>406 Not Acceptable</title>
12-07 04:58:33.130: D/aaaa(1243): </head><body>
12-07 04:58:33.130: D/aaaa(1243): <h1>Not Acceptable</h1>
12-07 04:58:33.130: D/aaaa(1243): <p>An appropriate representation of the requested resource /myfile.php could not be found on this server.</p>
12-07 04:58:33.130: D/aaaa(1243): <p>Additionally, a 404 Not Found
12-07 04:58:33.130: D/aaaa(1243): error was encountered while trying to use an ErrorDocument to handle the request.</p>
12-07 04:58:33.130: D/aaaa(1243): <hr>
12-07 04:58:33.130: D/aaaa(1243): <address>Apache Server at www.myURL.com Port 80</address>
12-07 04:58:33.130: D/aaaa(1243): </body></html>

Upvotes: 0

Views: 1067

Answers (3)

Darko Petkovski
Darko Petkovski

Reputation: 3912

Try something like this code, change it to your purpose, maybe it will help you

private void checkLogIn(final String username, final String password) {
                final String registerURL = "http://www.myURL.com/myfile.php?action=login&username="
                        + username + "&password=" + password;

                new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost(registerURL);

                        // httppost.setHeader("Accept", "application/json");
                        httppost.setHeader("Accept",
                                "application/x-www-form-urlencoded");
                        // httppost.setHeader("Content-type",
                        // "application/json");
                        httppost.setHeader("Content-Type",
                                "application/x-www-form-urlencoded");

                        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                                2);
                        nameValuePairs.add(new BasicNameValuePair("username",
                                username));
                        nameValuePairs.add(new BasicNameValuePair("password",
                                password));
                        try {
                            httppost.setEntity(new UrlEncodedFormEntity(
                                    nameValuePairs, "UTF-8"));
                        } catch (UnsupportedEncodingException e1) {
                            e1.printStackTrace();
                        }
                        try {
                            HttpResponse response = httpclient
                                    .execute(httppost);
                            HttpEntity entity = response.getEntity();
                            test = EntityUtils.toString(entity);

                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        } catch (ClientProtocolException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    protected void onPostExecute(Void result) {
                        try {
                            if (test.contains("false")) {
                                Toast.makeText(LogIn.this,
                                        "Wrong username or password",
                                        Toast.LENGTH_SHORT).show();
                            }
                            JSONArray arr = new JSONArray(test);
                            for (int i = 0; i < arr.length(); i++) {
                                JSONObject j = arr.getJSONObject(i);

                                employees.add(new Employee(j.getInt("id"), j
                                        .getString("name"), j
                                        .getString("surname"), j
                                        .getString("img_url"), j
                                        .getString("password"), j
                                        .getString("schedule_link"), j
                                        .getString("info"), j
                                        .getString("username"), j
                                        .getString("phone"),
                                        j.getString("dob"), j
                                                .getString("address"), j
                                                .getString("fb_link"), j
                                                .getString("status"), j
                                                .getString("email"), j
                                                .getString("position")));
                                if (LogIn.this.username.getText().toString().equals(
                                        j.getString("username")))
                                    prefs.edit()
                                            .putInt("userID", j.getInt("id"))
                                            .commit();

                            }
                            Intent i = new Intent(LogIn.this, Employees.class);
                            i.putExtra("emp", employees);
                            startActivity(i);
                            finish();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        dialog.dismiss();
                    };
                }.execute();
            }

Upvotes: 1

Anish
Anish

Reputation: 785

Try adding this before setEntity

output.setContentType("application/json");

Upvotes: 0

kumar_android
kumar_android

Reputation: 2263

Did you add this.?

httpPost.addHeader("content-type", "application/x-www-form-urlencoded")

Refer here

Upvotes: 0

Related Questions