So I am writing an Android application, and part of it is supposed to use GPS to acquire longitude/latitude. And those values are supposed to post to a PHP server I also have running. The function I have posting is as follows:
public void doAll() {
Double locLat, locLon;
try {
locLat = locManager.getLastKnownLocation(locProvider).getLatitude();
locLon = locManager.getLastKnownLocation(locProvider).getLongitude();
} catch (NullPointerException e) {
locLat = -1.0;
locLon = -1.0;
}
try {
HttpClient client = new DefaultHttpClient();
//we put all the parameters in the URL itself
HttpPost request = new HttpPost("http://fatalatour.com/database.php?function=get_all&latitude="+Double.toString(locLat)+"&longitude="+Double.toString(locLon));
ResponseHandler <String> responseHandler = new BasicResponseHandler();
//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//nameValuePairs.add(new BasicNameValuePair("latitude", Double.toString(locLat)));
//nameValuePairs.add(new BasicNameValuePair("longitude", Double.toString(locLon)));
//request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = client.execute(request, responseHandler);
Log.i("HOMI_RESPONSE", response.toString());
}
There is other code withing that but I believe that is all that actually affects the posting of locLat and locLon.
For the server end I have:
function get_all() {
$lat = trim($_GET['latitude']);
$lon = trim($_GET['longitude']);
// DEBUG
$f = fopen('debug.log', 'a');
fprintf($f, 'get_all: '.print_r($_REQUEST, true)."\n");
$result = mysql_query("SELECT * FROM homi_table");
$num = 0; //# of homicides
while ($row = mysql_fetch_assoc($result)) {
$d = distance($row['latitude'], $row['longitude'], $lat, $lon, "K");
if ($d < 100) { //number to change for distance filter
$num += 1;
echo "fatality:".$row['slug']."~".strtoupper($row['name']).", Age ".$row['age']."\n".$row['date']."\nhttp://projects.latimes.com/homicide/post/".$row['slug']."~".$row['latitude']."~".$row['longitude'];
// GH: limiting the number of results to 100
if ($num == 100) {
break;
}
}
};
echo $num;
fprintf($f, "get_all: returning: ".$num."\n");
}
Right now the issue seems to be the handling of $lat and $lon. When i hard code in a static number for each of those in the PHP the app works, yet when I leave it variable (as it should be), it fails. Any help would be greatly appreciated!
In Android application you are using POST request, in PHP you read GET parameters. Nothing else come to my mind.
The URL you've constructed looks like an HTTP Get, not a Post. Post would have the data being posted in the body of the request.
If you don't mind the parameters being exposed in the URL, I would simply change HTTPPost to HTTPGet in the Android code. If you don't want that stuff to be in the URL, you'll have to rework the Android post a little bit (something similar to your commented out code I believe) and change the php code to access the $_POST variable instead.
Related
I am making an android app.To fetch data from the app server running on my localhost using phpmyadmin, i am using below described php script:
<?php
$host = "localhost";
$db_user = "root" ;
$db_password = "" ;
$db_name = "FCM";
if(isset($_POST["Token"])){
$con = mysqli_connect($host,$db_user,$db_password,$db_name);
$sql = "select * from User";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('UserName'=>$row[0], 'EmailID'=>$row[1], 'UID'=>$row[2]
));
}
echo json_encode(array("users"=>$result));
mysqli_close($con);
}
?>
And in my java class, in order to gather the response, I am using Okhttp and below described code:
public void getDataOKHTTP() {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder().add("Token","").build();
Request request = new Request.Builder().url("http://.........../fcm/test.php").post(body).build();
System.out.println("# register a new token ");
try {
Response response= client.newCall(request).execute();
//response.header("Content-Type: application/json");
myJSON = response.body().string();
}catch (IOException e){
e.printStackTrace();
}
}
But when i run my app, i get,
com.example.apple.fetchdata, PID: 6092
android.os.NetworkOnMainThreadException.
I would be highly obliged if you could help me learn and resolve this problem.
thank you :)
All network operations has to be done on background thread, you're doing it on a main thread
I know it's a late answer for this question.
as Th3Dark0 said , All the networking calls must be done on background thread, you should use enque method rather then execute while making a call in OKHttp.
You can have a look at here if are you still interested :
Networking with OkHttp
I am developing an android app to create a new Quote in vTiger(ver 5.4) CRM server.
I was able to generate the new quote but the product_id and quantity that I sent for addition in quote details were not added in it. The other details are being shown in the new quote except the list of products, their quantities and pricing.
I have also studied the vTiger webservices tutorial but it was not helpful in this case.
I found an accepted answer of similar question but it is in php not in Android/JAVA.
This is how I am sending the details required to create a new quote in vTiger server.:-
try {
objectJson.put("subject", subject);
objectJson.put("account_id", accountId);
objectJson.put("bill_street", address);
objectJson.put("assigned_user_id", "19x1");
objectJson.put("conversion_rate", "1.000");
objectJson.put("currency_id", "21x1");
objectJson.put("hdnTaxType", "group");
objectJson.put("productid", productId);
objectJson.put("quantity", quantity);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String data = null;
try {
data = URLEncoder.encode("sessionName", "UTF-8")
+ "=" + URLEncoder.encode(sessionId, "UTF-8");
data += "&" + URLEncoder.encode("element", "UTF-8") + "="
+ URLEncoder.encode(objectJson.toString(), "ISO-8859-1");
data += "&" + URLEncoder.encode("elementType", "UTF-8") + "="
+ URLEncoder.encode(moduleName, "UTF-8"); //moduleName='Quotes'
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://vtiger_url/webservice.php?operation=create");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
}
catch(Exception ex)
{
}
The above code helps me to generate the quote without product details.
After studying the above mentioned php answer, I changed the URL that I was using in my code to this:- http://vtiger_url/webservice.php?total=23000&operation=create. This helped me to add the total amount to the newly created quote but I wasn't successful to add rest of the details using this method.
The answer you have found seems to be suitable, even if it's a php solution. The problem you descirbed:
I have tried this too but unfortunately I am not able to access Inventoryproductrel table.
maybe already indicates a lack of proper authentication or missing privileges. So my suggestion is to
Find out why you can't access the table Inventoryproductrel. Try to access that table using your authentication privileges (sessionID), examine the response for any hints and try to solve the table isn't accessible issue.
Finally follow the suggestions from this answer.
Just another hint. If you can successfully access that table via you web browser, than I would sniff the request and have a look at the http parameters and their values. Based on those findings you can modify your request.
Always consider, the web browser can only do the same as you android application.
These lines were added in existing code:-
JSONArray pdoInformation = new JSONArray();
try{
// Added these lines in try block to send product details
for(int i=0; i<productIds.size(); i++) {
JSONObject obj = new JSONObject();
obj.put("productid", productIds.get(i) );
obj.put("qty", quantities.get(i));
obj.put("listprice", listprices.get(i));
pdoInformation.put(obj);
}
objectJson.put("pdoInformation", pdoInformation);
}
Here product details were needed to be sent in a JSONArray with name as "pdoInformation".
for loop is used to send multiple product details.
Here productIds, quantities and listprices are three mandatory product details stored as ArrayList.
Why don't you use the web service to create products as well? That should be supported as per the documentation.
Once you create the products and get their ids, you can create a quote object that includes these ids. The objects and their fields are not very well documented for the rest APIs, so you could use the query/describe APIs to get as much information as possible about what data needs to be supplied for creating the different objects.
From the description of the Quotes module, you would need to include item_details which will contain the product and quantity information. The exact field name and format can be obtained by the describe API as described in the web service documentation
To get a description of the vTiger objects
String modeleName = "Quotes"; //Use Products if you want a description of the Products module
String data = null;
try {
data = URLEncoder.encode("sessionName", "UTF-8")
+ "=" + URLEncoder.encode(sessionId, "UTF-8");
data += "&" + URLEncoder.encode("elementType", "UTF-8") + "="
+ URLEncoder.encode(moduleName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String text = "";
BufferedReader reader=null;
System.out.println(data);
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://vtiger_url/webservice.php?operation=describeobject");
// Send GET data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
} catch(Exception ex) {
}
Note that it's pretty much the same as what you are doing, only the url & parameters are different, and the request type is GET instead of POST
To create a product, you would follow the same procedure as you did for the quote, only the url and parameters would be different
#help as far i understand your question is how to send JsonObject with data to specified Server is that correct ? if it is the correct then i suggest you to use Volley library for networking and here are many examples that may useful to you .http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/ and http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
Just go through it. It provides easiest way to perform networking operations and also cancellation of request is also possible with this library.
Sample Code:
final String URL = "SERVER_URL";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
Using this code you can send your data to your server and at server side you can use php code to receive this jsondata and parse it.
Thanks.
My goal is to rapidly make posts to a server from appengine(java). I am attempting to do this using UrlFetchService.fetchAsync. I have been basing my code after this blog post. I have been able to make the request using the code below, however I get some strange behavior:
private void futureRequests() {
URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
URL url = new URL("https://someserver.com");
FetchOptions fetchOptions = FetchOptions.Builder.withDefaults();
fetchOptions.doNotValidateCertificate();
fetchOptions.setDeadline(60D);
ArrayList<Future<HTTPResponse>> asyncResponses = new ArrayList<Future<HTTPResponse>>();
for (int i = 0; i < postDatas.size(); i++) {
HTTPRequest request = new HTTPRequest(url, HTTPMethod.POST, fetchOptions);
request.setPayload(postDatas.get(i).getBytes(UTF8));
HTTPHeader header = new HTTPHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
request.setHeader(header);
header = new HTTPHeader("Content-Length", Integer.toString(postDatas.get(i).getBytes().length));
request.setHeader(header);
header = new HTTPHeader("Authorization", "auth=" + authToken);
request.setHeader(header);
Future<HTTPResponse> responseFuture = fetcher.fetchAsync(request);
asyncResponses.add(responseFuture);
}
for (Future<HTTPResponse> future : asyncResponses) {
HTTPResponse response;
try {
response = future.get();
int responseCode = response.getResponseCode();
resp.getWriter().println("response: " + responseCode);
logger.warning("Response: " + responseCode);
} catch (Exception e) {
}
}
}
The strange behavior is that I get duplicate posts on the server, and according to my appstats page I use 10x-20x more urlFetches than what was added with the code above. Below is my appstats screen:
There are more urlFetch calls that could not fit on the screen. It appears that the requests are still completing in a synchronous fashion(circled items), but there are many urlFetches that appear to go on at the same time. My question is how am I getting all this calls to urlFetch when I only had 14 Future ?? Could the server be giving an error or 503 and urlFetch retrying until it goes through? And how can I be getting 2 posts for each request??
I understand that I could use the task queue to do asyc request, however I am dealing with a relatively low number of request(20-100) and the cold start time of ramping up another instance would probably make this not a good option for my situation. Can anyone explain this behavior or have experience with this?
This was simply a mistake in my code that was causing my app to make more request than I thought..
Okay, so my app will find the word you type into the text box from a database inside my website.. and it will find the "word" if there is more than 1 "word" it will go through each and pick a random "reply"
How can I do it so that if it can't find the word "hey" it will look for similar things like "he" etc?
Here's my PHP:
<?php
// Connect to database
mysql_connect("server", "db username", "db password");
mysql_select_db("db405677000");
// If something is received
if($_POST)
{
if($_POST['action'] == "ask")
{
// Filter it to prevent SQL injections
$text = mysql_real_escape_string($_POST['stringdata']);
// Search it on the database
$q = mysql_query("SELECT `reply` FROM `poka` WHERE `word` = '$text' ORDER BY RAND()");
// Show result
if($r = mysql_fetch_assoc($q))
echo $r['reply'];
else
echo "Cannot find a reply";
}
elseif($_POST['action'] == "teach")
{
// Filter it to prevent SQL injections
$word = mysql_real_escape_string($_POST['word']);
$answer = mysql_real_escape_string($_POST['answer']);
// Insert it to the database
if( mysql_query("INSERT INTO `poka` VALUES(NULL, '$word', '$answer')") )
echo "ok";
else
echo "fail";
}
}
?>
And here is my java part where it actually gets the response:
public void responseGet(String textRequest)
{
EditText textbox = (EditText)findViewById(R.id.chat);
textbox.setText("");
TableLayout chatbox = (TableLayout)findViewById(R.id.chatbox);
if(canReply == false)
{
TableRow tr1 = new TableRow(this);
tr1.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(this);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://monaiz.net/get.php");
String responseStr = "";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("stringdata", textRequest));
nameValuePairs.add(new BasicNameValuePair("action", "ask"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity( );
responseStr = EntityUtils.toString( entity ).replace("\\", "");
} catch (Exception e) {
// TODO Auto-generated catch block
}
textview.setText(responseStr);
// textview.getTextColors(R.color.)
textview.setTextColor(Color.BLACK);
textview.setGravity(Gravity.LEFT);
tr1.addView(textview);
// Convert dp to px
int padding_in_dp = 7;
final float scale = getResources().getDisplayMetrics().density;
int padding_in_px = (int) (padding_in_dp * scale + 0.5f);
tr1.setPadding(padding_in_px, 0, padding_in_px, 0);
tr1.setBackgroundResource(R.drawable.pokaspeak);
tr1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent startNewActivityOpen = new Intent(main.this, TeachmeDialog.class);
startActivityForResult(startNewActivityOpen, 0);
}
});
chatbox.addView(tr1, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
canReply = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
ScrollView s = (ScrollView) findViewById(R.id.SV);
s.fullScroll(View.FOCUS_DOWN);
}
},100);
}
}
You can use PHP function called metaphone.
There is also a function called soundex that return a numerical code for a word that represents its sound. Words that sound similar will have the same soundex code. You could have a table with words and their soundex codes that you could use to look up similar sounding words. You could then sort them using their levenshtein distance
Similar to soundex() metaphone creates the same key for similar sounding words. It's more accurate than soundex() as it knows the basic rules of English pronunciation. The metaphone generated keys are of variable length.
In MySQL you can make use of the SOUNDEX function. You just need to change your where clause in the query from
...WHERE `word` = '$text'...
to
...WHERE soundex(word) = soundex('$text')...
or even better you can use SOUNDS LIKE operator as
...WHERE word sounds like '$text'...
Hope this helps
Probably this is often problem, but I can't solve it.
I need to automaticallly fill out some fields on the web form, which is given from server.
I use Apache HttpClient to make more easy my life)
By now, one can consider my steps to acheive the aim:
1. I have not certificate to http://trac.edgewall.org/ so I download this software and install locally and at finish I'll have to create NewTicket.
2. I locally use Trac without any SSL(SSL tunnel). (It's not difficult to change my program to be able to use HTTPS).
3. By now, I can authenticate and perform GET request, but I can't perform POST request
4. For instance: I perform GET request to the http://localhost:8000/tracenvir/newticket .
This (~/newticket) page looks as following:
http://s04.radikal.ru/i177/0912/cb/d43971cebc02.png
And as response I have : (part of it)
"input type="text" id="field-summary" name="field_summary" size="70" "
"textarea id="field-description" name="field_description" class="wikitext" rows="10" cols="68"/textarea"'
5. So, I write this:
int status = 0;
int cookLength=0;
Cookie[] cookies = null;
HttpClient client = new HttpClient();
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
HttpState initialState = new HttpState();
client.setState(initialState);
//**********//
//**Log in**//
//**********//
GetMethod login = new GetMethod("http://localhost:8000/tracenvir/login");
client.getState().setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("rauch", "qwert"));
login.setDoAuthentication(true);
System.setProperty("javax.net.ssl.trustStore", "/home/rauch/NetBeansProjects/jssecacerts");
try {
status = client.executeMethod(login);
System.out.println("response code = "+status);
cookies = client.getState().getCookies();
cookLength = cookies.length;
for(int i=0;i (less than) cookLength;i++) {
System.out.println(cookies[i].toString());
}
login.releaseConnection();
} catch(IOException ex) {
ex.printStackTrace();
}
//*********************//
//**Create New Ticket**//
//*********************//
PostMethod post = new PostMethod("http://localhost:8000/tracenvir/newticket");
NameValuePair[] data = {
new NameValuePair("field-summary","second error"),
new NameValuePair("field-descryption","Some stupid descryption..."),
new NameValuePair("field-type","defect"),
new NameValuePair("field-priority","major"),
new NameValuePair("field-version","1.0"),
new NameValuePair("field-owner","moscow server"),
new NameValuePair("submit","create ticket"),
};
//post.setRequestBody(data);
post.addParameters(data);
post.addRequestHeader("Referer","http://localhost:8000/tracenvir/login");
for(int i=0;i (less than) cookLength;i++) {
initialState.addCookie(cookies[i]);
}
client.setState(initialState);
try {
status = client.executeMethod(post);
System.out.println("response code = "+status);
byte[] buf = new byte[10];
int r=0;
BufferedInputStream is = new BufferedInputStream(post.getResponseBodyAsStream());
while((r = is.read(buf)) > 0) {
System.out.write(buf, 0, r);
}
post.releaseConnection();
} catch(IOException ex) {
ex.printStackTrace();
}
}
And I have this:
400 Error: Bad Request
Missing or invalid form token. Do you have cookies enabled?
What's wrong?
As response on GET request I get this:
response code = 200
trac_auth=38144ec2830678183afebf0b14c51721
trac_form_token=e9648f17987551b8f97e1953
Probably I nedd change this:
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
http://www.google.com/support/toolbar/bin/answer.py?hl=en&answer=47972
I think above link will help u on this topic. its provide video also.. i hope your query will be solved
http://www.formautofill.com/
This site will give you a software which will provide auto form filler. provided by microsoft.
Ok. This below link is about post method . i think it might help u.
http://www.willmaster.com/library/manage-forms/automatic-form-submission-to-a-cgi-program.php
give me reply. if it doesn't.