简体   繁体   中英

Cannot POST or GET data onto Web Server from Android

I had try to POST a simple query string ( tag=register&uname.... )

But it seems that the parameters are not sent to the local web server (Apache)

Below is a piece of the ANDROID code I'm using.

I know that the POST didn't work because the result sent back to ANDROID is a null JSON object

public JSONObject getJSONFromUrl(String url, List<Pair<String, String>> params) throws MalformedURLException {

    // _url = http://192.168.0.10/ibiti_api/
    URL _url = null;
    String dataToPost = null;
    try {
        dataToPost = this.getQuery(params);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    //getQuery(params) send back a string like : tag=register&uname=....
    HttpURLConnection urlConnection = null;
    OutputStreamWriter wr = null;
    JSONObject _oUser = null;
    try {
        _url = new URL(url);
        urlConnection = (HttpURLConnection)_url.openConnection();
        urlConnection.setRequestMethod("POST");
        //urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //urlConnection.setRequestProperty( "Accept", "*/*" );
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setChunkedStreamingMode(0);
       // urlConnection.connect();
        //POST request
        wr = new OutputStreamWriter(urlConnection.getOutputStream ());
        wr.write(dataToPost);
        in = urlConnection.getInputStream();
        //wr.flush();
        _oUser =  readStream(in); // Result is an objet null because nothing is POST
        wr.close();
        in.close();
        urlConnection.disconnect();

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

    return _oUser;

}

i used :

static OutputStream out = null;
InputStream in = null;
//to send the parameters : 
urlConnection = (HttpURLConnection)_url.openConnection();
out = urlConnection.getOutputStream();
        wr = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
        wr.write(dataToPost);
        wr.flush();
        wr.close();
        out.close();
        int httpResponse = urlConnection.getResponseCode();
        in = urlConnection.getInputStream();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM