How to pass an argument with POST using HttpUrlConnection

落爺英雄遲暮 提交于 2019-12-11 11:07:20

问题


EDIT: I figure out that wrapping the OutputStreamWriter in a BufferedWriter was causing the problem, so got rid of the wrapper and my POST goes through. Still wondering why the BufferedWriter was the cause.

I apologize in advance, as I am just beginning to teach myself all about databases, communication between an app and a server/database, and php.

Other similar questions asked have not provided an answer.

I am having some trouble discerning what I'm missing when it comes to making a simple POST using HttpUrlConnection from my android application to a php script on a locally hosted server. I need to take a user ID from the android application, pass that to the php script as an argument, and perform a lookup of that ID in the database table called users. I also would like to use methods and classes that are not deprecated.

I have included Internet permissions in the android manifest. I am using XAMPP, and I have verified that my servers are running, and if I access the url through a web browser I get the JSON response I am looking for.

My only logcat message is an IOException, which occurs just after writing to the output stream. EDIT: The specific exception is "unexpected end of stream".

Here is the code in my AsyncTask class:

protected String doInBackground(String... params) {

    String userID = params[0];
    Pair<String, String> phpParameter = new Pair<>("userID", userID);
    String result = "";

    try {
        URL url = new URL("url of locally-hosted php script");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        // prepare request
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setFixedLengthStreamingMode(userID.getBytes("UTF-8").length);

        // upload request
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(phpParameter.first + "=" + phpParameter.second);
        writer.close();
        outputStream.close();

        // read response
        BufferedReader in = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()));

        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) { response.append(inputLine); }
        in.close();

        result = response.toString();

        // disconnect
        urlConnection.disconnect();
    } catch (MalformedURLException e) {
        Log.e("Malformed URL Exception", "Malformed URL Exception");
    } catch (IOException e) {
        Log.e("IOException", "IOException");
    }

    return result;
}

And here is my php script on the server. I also need a little help with prepared statements, so don't beat me up over the 'id = 1':

<?php

mysql_connect("host","username","password");

mysql_select_db("Database");

print($_POST);

$sql = mysql_query("select * from users where id = 1");

while($row = mysql_fetch_assoc($sql))
$output[] = $row;

print(json_encode($output)); // this will print the output in json
mysql_close();

?>

回答1:


To post from android:

public class HttpURLConnectionHandler
{
     protected String urlG = "http://192.168.43.98/yourdirectory/";
     public String sendText(String text)
    {
    try {
        URL url = new URL(urlG+"receiveData.php");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");

        // para activar el metodo post
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream wr = new DataOutputStream(
            conn.getOutputStream());
        wr.writeBytes("mydata="+text);
        wr.flush();
        wr.close();

        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
   }
   catch(Exception e){ return "error";}
   }
}

php file:

$x = $_POST['mydata'];
echo $x;  



回答2:


Bro, using a custom lib like loopjs async httplib would be simpler. Check out this code sample of what you are trying to do,

Why should you use it you ask? All exceptions and async tasks are handled in the background making your code base simpler.

    AsyncHttpClient client = new AsyncHttpClient();
client.post(YOUR_POST_URL, new AsyncHttpResponseHandler() {

@Override
public void onStart() {
    // called before request is started
}

@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
    // called when response HTTP status is "200 OK"
}

@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
    // called when response HTTP status is "4XX" (eg. 401, 403, 404)
}

@Override
public void onRetry(int retryNo) {
    // called when request is retried
}
    });



回答3:


Looks like I fixed it!

I changed

BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(phpParameter.first + "=" + phpParameter.second);

to

OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(userID);

For some reason, the act of wrapping the output stream writer in a buffered writer was breaking it. I don't know why.

Once I made the above change, I received an error saying that the stream was expecting 1 byte but received 8, so I wrote only userID, which is what I passed to setFixedLengthStreamingMode anyway.



来源:https://stackoverflow.com/questions/31324156/how-to-pass-an-argument-with-post-using-httpurlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!