Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6241495
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T11:46:40+00:00 2026-05-24T11:46:40+00:00

I’m trying to do a request to a server with some POST parameters, I

  • 0

I’m trying to do a request to a server with some POST parameters, I have used some code that I found here: Using java.net.URLConnection to fire and handle HTTP requests

The problem is that all values becomes “0” when i write them out on the php page on the server, except the first numbers in the ssn. Also, the response i get back to the java code, does not have “charset=UTF-8” in the “content-type” member of the header. But as you can see in the php/html code, I don’t change the header anywhere.

Android code:

public static String testCon()
    {
        String url = "http://xxx.xxx.se/postReciverTest.php";
        String charset = "UTF-8";
        String param1 = "Test";
        String param2 = "Test2";
        String param3 = "123456-7899";
        // ...

        String query = null;

        try
        {
            query = String.format("fname=%s&sname=%s&ssn=%s", 
                    URLEncoder.encode(param1, charset), 
                    URLEncoder.encode(param2, charset), 
                    URLEncoder.encode(param3, charset));
        } 

        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        URLConnection connection = null;
        try {
            connection = new URL(url).openConnection();
            } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.setDoOutput(true); // Triggers POST.
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = null;
        try {
             try {
                output = connection.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }


             try {
                output.write(query.getBytes(charset));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


        } finally {
             if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
        }

        InputStream response = null;
        try {
            response = connection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        int status;
        try {
            status = ((HttpURLConnection) connection).getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
            System.out.println(header.getKey() + "=" + header.getValue());
        }

        String contentType = connection.getHeaderField("Content-Type");
        charset = null;
        for (String param : contentType.replace(" ", "").split(";")) {
            if (param.startsWith("charset=")) {
                charset = param.split("=", 2)[1];
                break;
            }
        }

        charset = "UTF-8"; //this is here just because the header don't seems to contain the info and i know that the charset is UTF-8 
        String res = "";
        if (charset != null) {
            BufferedReader reader = null;
            try {
                try {
                    reader = new BufferedReader(new InputStreamReader(response, charset));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                try {
                    for (String line; (line = reader.readLine()) != null;) {
                        // ... System.out.println(line) ?
                        res += line;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } finally {
                if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
            }
        } else {
            // It's likely binary content, use InputStream/OutputStream.
        }

        return null;
    }

page that i sent the request to:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
Test
<?
    echo $_POST["fname"] + "<br />";
    echo $_POST["sname"] + "<br />";
    echo $_POST["ssn"] + "<br />";
?>

</body>
</html>

So the result I get in the “res” variable is the html code with “00123456” insted of:
“Test
Test2
123456-7899”

This is not my field, so it would be nice if the answer(s) is fairly easy to understand 🙂

Thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T11:46:41+00:00Added an answer on May 24, 2026 at 11:46 am

    I’ve stayed away from using URLConnection and instead have been using DefaultHttpClient. Here are 2 simple methods which sends off either GET or POST and returns a String response

    The important part to note is where you add name -> value pairs to the HttpPost object:
    nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));

    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    Here is an example:

    Map<String, String> params = new HashMap<String, String>(3);
    params.put("fname", "Jon");
    params.put("ssn", "xxx-xx-xxxx");
    params.put("lname", "Smith");
    ...
    String response = execRequest("http://xxx.xxx.se/postReciverTest.php", params);
    

    –

    public static String execRequest(String url, Map<String, String> params) {
        try {
            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
            HttpPost httpPost = null;
            HttpGet httpGet = null;
            if(params == null || params.size() == 0) {
                httpGet = new HttpGet(url);
                httpGet.setHeader("Accept-Encoding", "gzip");
            }
            else {
                httpPost = new HttpPost(url);
                httpPost.setHeader("Accept-Encoding", "gzip");
    
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                for(String key: params.keySet()) {
                    nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
            HttpResponse httpResponse = (HttpResponse)defaultHttpClient.execute(httpPost == null ? httpGet : httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if(null != httpEntity) {
                InputStream inputStream = httpEntity.getContent();
                Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
                if(contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    inputStream = new GZIPInputStream(inputStream);
                }
                String responseString = Utils.convertStreamToString(inputStream);
                inputStream.close();
    
                return responseString;
            }
        }
        catch(Throwable t) {
            if(Const.LOGGING) Log.e(TAG, t.toString(), t);
        }
        return null;
    }
    
    public static String convertStreamToString(InputStream inputStream) {
        byte[] bytes = new byte[1024];
        StringBuilder sb = new StringBuilder();
        int numRead = 0;
        try {
            while((numRead = inputStream.read(bytes)) != -1)
                sb.append(new String(bytes, 0, numRead));
        }
        catch(IOException e) {
            if(Const.LOGGING) Log.e(TAG, e.toString(), e);
        }
        String response = sb.toString();
        if(Const.LOGGING) Log.i(TAG, "response: " + response);
        return response;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to create an if statement in PHP that prevents a single post
I have thousands of HTML files to process using Groovy/Java and I need to
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to loop through a bunch of documents I have to put
I have some data like this: 1 2 3 4 5 9 2 6

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.