简体   繁体   中英

How do I retrieve two field values received from an HTTP POST to PHP?

Here is what I am trying to do.

From my Android App code I do an HTTP POST which is as below

HttpPost httppost = new HttpPost("http://xyz.com/Retrieve.php");

The PHP code is supposed to send back an image and an URL.

$q=mysql_query("SELECT image, url FROM testblob WHERE id = 'id[0]'");
list($data) = mysql_fetch_row($q);
echo $data;

Now in my Android code I do the following and the image is retrieved perfect from the response but how do I retrieve the URL as well.

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();

I retrieve the image as below and this part works.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while ((n=is.read(buf))>=0)
    {
    baos.write(buf, 0, n);
    }
    is.close();
    byte[] bytes = baos.toByteArray();
    Bitmap bitmap2 = null;
    bitmap2 = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

So I would like to know if both the image and the url is received in the InputStream is object and if yes how do I retrieve the URL out of it?

Thanks for all the help.

It's a bit more overhead, but it might be easier if you make 2 requests to your server. That way you don't have to worry about separating the bytes.

For the URL request, return a text response.

For the image request, return the bytes (as you're doing now).

You have several options here; here is one. Instead of simply echoing out the bytes for the image from PHP you can encode the image and URL using json_encode() .

For example:

$q = $pdo->prepare("SELECT image, url FROM testblob WHERE id = ?");
$q->execute(array($id[0]));
header("Content-Type: application/json");
echo json_encode($q->fetch(PDO::FETCH_NUM));

On the Java side you'll have the read the response from the URL and then parse it appropriately into a JSON object .

I've updated the example to use PDO instead of the old database access functions. You can read up on PHP Data Objects here .

1) Your php code do not use post variable so you retrieve always the same image.

2) After setting the output type you can stream the image back to client;

$q=mysql_query("SELECT image FROM testblob WHERE id = '".$_POST['id']."'");
$row = mysql_fetch_row($q);
header("Content-Type: image/jpeg");
echo $row[0];

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