Search code examples
javaandroidhttp-request

Java HTTP-Request with POST-Data


I wrote the following code in java to send some data via POST-Variables to a PHP-File of my website and then I want to get the source code of this website.

public DatabaseRequest(String url, IDatabaseCallback db_cb)
        {
            this.db_cb = db_cb;
            site_url = url;
            client = new DefaultHttpClient();
            request = new HttpPost(site_url);
            responseHandler = new BasicResponseHandler();
            nameValuePairs = new ArrayList<NameValuePair>(0);
        }

        public void addParameter(List<NameValuePair> newNameValuePairs)
        {
            nameValuePairs = newNameValuePairs;
        }

        public void run()
        {
            db_cb.databaseFinish(getContent());
        }

        public String[] getContent()
        {

            String result = "";
            try {
                request.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
                result = client.execute(request, responseHandler);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String[] result_arr = result.trim().split("<br>");
            for (int i = 0; i < result_arr.length; i++)
            {
                result_arr[i] = result_arr[i].trim();
            }
            return result_arr;
        }

When I want to run this code, then eclipse throws the following error message: Error Message


Solution

  • Try this:

    // executes the request and gets the response.
    HttpResponse response = client.execute(httpPostRequest);
    // get the status code--- 200 = Http.OK
    int statusCode = response.getStatusLine().getStatusCode();
    
    HttpEntity httpEntity = response.getEntity();
    responseBody = httpEntity.getContent();    
    
    if (statusCode = 200) {
        // process the responseBody. 
    }
    else{
        // there is some error in responsebody
    }
    

    EDIT: To handle UnsupportedEncodingException

    Before making HTTP request you need to encode the post data in order to convert all string data into valid url format.

    // Url Encoding the POST parameters
    try {
        httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
    }
    catch (UnsupportedEncodingException e) {
        // writing error to Log
        e.printStackTrace();
    }