1

I want to call the following URL:

http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"}

Use this address to add a new user to the database. To do this I use HttpURLConnection in my AsyncTask class

try {

                URL myUrl = new URL(params[0]);
                HttpURLConnection conn = (HttpURLConnection) myUrl.openConnection();
                conn.setReadTimeout(10000 );
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                // Starts the query
                conn.connect();
                int response = conn.getResponseCode();

                Log.d("lab", "The response is: " + response);

                statusMap.put("addUser", Integer.toString(response));

                Log.d("lab", "URL: " + params[0]);

            }catch (Exception e){
                Log.d("lab", "Error2: " + e.getMessage());
            }

params[0] = http://192.168.0.196:8080/openapi/localuser/set?{"syskey":"1234","usrname":"256","usrpwd":"556"}

Unfortunately, this call is not working. I do not get the error. catch returns null

2
  • 1
    From your param link, I think you only need conn.setRequestMethod("GET"); and don't need conn.setDoInput(true);. Beside of that, you should use "Log.getStackTraceString(e)" instead of e.getMessage() then add the logcat here. Commented Aug 11, 2015 at 10:54
  • When I remove conn.setDoInput(true) my code is working. Thanks! Commented Aug 11, 2015 at 10:58

3 Answers 3

1

Try like this way. You need to add few line in your code.

public JSONObject makeHttpRequest(String requestURL, JSONObject register) {

        try {

            url = new URL(requestURL);

            connection = (HttpURLConnection) url.openConnection();

            connection.setReadTimeout(150000);
            connection.setConnectTimeout(150000);

            connection.setAllowUserInteraction(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            connection.setFixedLengthStreamingMode(register.toString().getBytes().length);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());

            outputStream.write(register.toString());

            outputStream.flush();

            Log.e("URL", connection.getURL().toString());
            Log.e("JSONObject", register.toString());
        } catch (Exception e) {
            Log.e("MAIN Exception", e.toString());
        }
        try {

            int statuscode = connection.getResponseCode();

            if (statuscode == HttpURLConnection.HTTP_OK) {
                is = connection.getInputStream();
            } else {

            }
        } catch (IOException e) {
            Log.e("IOException", e.toString());
        }

        try {

            rd = new BufferedReader(new InputStreamReader(is));

            response = new StringBuffer();

            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\n');
            }
            Log.e("Response", response.toString() + " ");

            rd.close();
        } catch (IOException e) {
            Log.e("BUFFER_READER", e.toString());
        } catch (NullPointerException e) {
            Log.e("NullPointerException", e.toString());
        } finally {
            connection.disconnect();
        }

        try {


            return new JSONObject(response.toString());
        } catch (JSONException e) {
            Log.e("JSONException", e.toString());

        }
        return null;
    }

Also You are using localHost you must have emulator which can connect to localhost. Unless it will not going to work on any device.

Sign up to request clarification or add additional context in comments.

Comments

1

try this :

 private String post(String url) throws JSONException {
    JSONObject json = new JSONObject();
    try {
        String query = "";
        String EQ = ":";
        String AMP = "&";
        for (NameValuePair param : parameters) {
            query = json.put(param.getName(), param.getValue()) + ",";

        }

        // url+= "?" + query;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        if (parameters != null) {

            StringEntity se = new StringEntity(query.toString());
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));

            post.setEntity(se);

            Log.d("POSTQuery", url + parameters);
        }

        HttpResponse response = client.execute(post);
        StatusLine statusLine = response.getStatusLine();
        Log.d("Status Code", "" + statusLine.getStatusCode());
        if (statusLine.getStatusCode() == 200) {
            return StringifyResponse(response);
        }

        Log.d("POSTQuery", url);

        // Log.d("response", response.toString());
        return StringifyResponse(response);

    } catch (ClientProtocolException e) {
    } catch (IOException e) {
        Log.d("response", e.toString());
        return "IOException";
    }

    return null;
}

2 Comments

HttpClient is deprecated now. You shouldn't use it.
yeah,you are right @Minhtdh as Android developer mentioned here ,It's deprecated from API level 22.
0

You need to format all url querystring and then use outputwriter to flush the data :

// Create data variable for sent values to server  

        String data = URLEncoder.encode("syskey", "UTF-8") 
                     + "=" + URLEncoder.encode("1234", "UTF-8"); 

        data += "&" + URLEncoder.encode("usrname", "UTF-8") + "="
                    + URLEncoder.encode("256", "UTF-8"); 

        data += "&" + URLEncoder.encode("usrpwd", "UTF-8") 
                    + "=" + URLEncoder.encode("556", "UTF-8");

and then flush the data:

        URLConnection conn = url.openConnection(); 
        conn.setDoOutput(true); 
        OutputStreamWriter wr = new  OutputStreamWriter(conn.getOutputStream()); 
        wr.write( data ); 
        wr.flush(); 

Link here : http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.