Question

I am trying to do HTTPRequest Post via Google App Engine. This is what I have so far

URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(########);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);

Here I need to put some paired values (ie. "email","hi@example.com" etc) Since setPayload accept byte[] I have no idea how to convert my paired values into byte.

I have searched other posts but I am very stuck.

EDIT: I have changed to this but it is still not working

byte[] data = ("EMAIL=bo0@gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000;").getBytes();
try {
URL url = new URL("http://www.bo.x10.mx/nPost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);

This is what I have on php website.

<?php
include "path/conf.php"; //logging into database works
$tb_name = 'Post';
$EMAIL=$_POST['EMAIL'];
$TITLE =$_POST['TITLE'];
$COMMENT =$_POST['COMMENT'];
$PRICE =$_POST['PRICE'];
if(!isset($EMAIL) || !isset($TITLE ) || !isset($PRICE )|| !isset($COMMENT)){
header('HTTP/1.0 412 Precondition Failed', true, 412);
die('Bad data');
}
$sql="INSERT INTO $tb_name(EMAIL, TITLE, COMMENT, PRICE) VALUES ('$EMAIL', '$TITLE ', '$COMMENT ', '$PRICE ')";
$result=mysql_query($sql);
if($result==TRUE){
echo "successfully inserted into table!";}
else{
echo "error in inserting into table!";
header('HTTP/1.0 500 Internal Server Error', true, 500);}
ob_end_flush();
exit();
?>

EDIT2: This is a working code

try{
byte[] data = ("EMAIL=bo0@gmail.com&TITLE=evolution&COMMENT=comments&PRICE=5000").getBytes("UTF-8");
URL url = new URL("http://www.box.com/nost.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
request.setPayload(data);
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
}

My database string field is of type UTF-8

Was it helpful?

Solution

You create a String with the request body, and then you get the byte array. For example we have:

URL url = new URL("http://myurl.com/myfile.php");
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST);
String body = "email=" + email + "&mpla=" + mpla;
request.setPayload(body.getBytes("UTF-8"));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top