How to send data to php server and receive data to android - java

I'm a newbie in android programming and I want to sent data to php server and receive data to show in android
but I have no idea to create it, I don't no to use library? and Can give some example for me to practice about it.
ps. sorry my english is not good.
example Myphp "xxx.xxx.x.x/api.php"
$keyword = $_GET['keyword'];
$index= $_GET['index'];
$path = "http://xxxxxxx/webservice/&query=".urlencode($keyword)."&index=".$index."";
$jsondata = file_get_contents($path);
$jsons = json_decode($jsondata,true);
echo json_encode($jsons);
I want to send keyword and index from edittext to php server and receive json data to show listview.

HttpURLConnection can be used for get,put,post,delete requests :
try {
// Construct the URL
URL url = new URL("http://xxxxxxx/webservice/&query="
+keyword.getText().toString()
+"&index="+index.getText().toString());
// Create the request
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
}
JsonStr = buffer.toString(); //result
} catch (IOException e) {
}
where keyword and index will be your EditText Variables.

Related

How to pass Form data variables to the rest api call from stand alone java code

I got a situation to test the REST API's Delete call through Java code. I need to pass Form Data with 2 variables as below screenshot to the api request. someone please route me how to do that..
try {
URL url = new URL("http://localhost:8999/testsource");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("session", "Cii2vEBZDplu5fI9JNXiM5");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
Your question isn't very clear but I'll make an attempt to answer it based on the assumption that your form data contains two fields which are:
id
permanentDelete
String data = "id=the-id-goes-here&permanentDelete=yes-or-no-goes-here";
byte[] bytesToSend = data.getBytes(StandardCharsets.UTF_8);
OutputStream outputStream = conn.getOutputStream();
outputStream.write(bytesToSend);

Java client POST to php script - empty $_POST

I have researched extensively and cannot find a solution. I have been using the solutions provided to other users and it does not seem to work for me.
My java code:
public class Post {
public static void main(String[] args) {
String name = "Bobby";
String address = "123 Main St., Queens, NY";
String phone = "4445556666";
String data = "";
try {
// POST as urlencoded is basically key-value pairs
// create key=value&key=value.... pairs
data += "name=" + URLEncoder.encode(name, "UTF-8");
data += "&address=" +
URLEncoder.encode(address, "UTF-8");
data += "&phone=" +
URLEncoder.encode(phone, "UTF-8");
// convert string to byte array, as it should be sent
byte[] dataBytes = data.toString().getBytes("UTF-8");
// open a connection to the site
URL url = new URL("http://xx.xx.xx.xxx/yyy.php");
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
// tell the server this is POST & the format of the data.
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(dataBytes.length);
conn.getOutputStream().write(dataBytes);
conn.getInputStream();
// Print out the echo statements from the php script
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while((line = in.readLine()) != null)
System.out.println(line);
in.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
and the php
<?php
echo $_POST["name"];
?>
The output I receive is an empty line. I tested to see if it was a php/server side issue by making an html form that sends data over to a similar script and prints the data on the screen and that worked. But, for the life of me, I cannot get this to work with a remote client.
I am using Ubuntu server and Apache.
Thank you in advance.
The problem is actually in what you read as output. You are doing two requests:
1)conn.getInputStream(); - sends POST request with desired body
2)BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream())); - sends empty GET request (!!)
Change it to:
// ...
conn.getOutputStream().write(dataBytes);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
and see result.

Java app store receipt validation

I am trying to validate an Apple App Store receipt from a Java service. I can not get anything back other than an error 21002, "Receipt Data Property Was Malformed". I have read of others with the same problem, but, have not see a solution. I thought this would be fairly straight forward, but, have not been able to get around the error. Here is my code:
EDIT By making the change marked // EDIT below, I now get an exception in the return from the verifyReceipt call, also makred //EDIT:
String hexDataReceiptData = "<30821e3b 06092a86 4886f70d 010702a0 .... >";
// EDIT
hexDataReceiptData = hexDataReceiptData.replace(">", "").replace("<", "");
final String base64EncodedReceiptData = Base64.encode(hexDataReceiptData.getBytes());
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put("receipt-data",base64EncodedReceiptData);
}
catch (JSONException e)
{
e.printStackTrace();
}
URL url = new URL("https://sandbox.itunes.apple.com/verifyReceipt");
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
//Send request
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(jsonObject.toString());
wr.flush();
//Get Response
BufferedReader rd =
new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder httpResponse = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
{
httpResponse.append(line);
httpResponse.append('\r');
}
wr.close();
rd.close();
// EDIT
// {"status":21002, "exception":"java.lang.IllegalArgumentException"}
As posted here: Java and AppStore receipt verification, do the base64 encoding in iOS and send to the server. But, why?

getContentLength returning 1225, real length 3365

I am currently working with android and i am using a http connection with some headers (i havent included them or the real url for security purposes) to get a JSON response from an API, and feeding that response back into the application. The problem that i am having is that when using the getContentLength method of the http request, the wrong length is being returned (wrong length returned is 1225, the correct length in characters of the JSON array is 3365).
I have a feeling that the JSON is not fully loaded when my reader starts to read it, and as such is only reading the loaded JSON at that point. Is there any way around this, possibly using a delay on the HTTP connection or waiting until it is fully loaded to read the data?
URL url = new URL("https://www.exampleofurl.com");
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
int responseCode = request.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = request.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
long contentLength2 = Long.parseLong(request.getHeaderField("Content-Length"));
Log.i("contentLength: ", "Content: " + contentLength2);
I generally don't recommend always relying on "Content-Length" as it may not be available (you get -1), or perhaps affected by intermediate proxy.
Why don't you just read your stream until it is exhausted into memory buffer (say, StringBuilder) and then get the actual size, for example :
BufferedReader br = new BufferedReader(inputStream); // inputStream in your code
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
// finished reading
System.out.println("data size = " + sb.length());
JSONObject data = new JSONObject(sb.toString());
// and don't forget finally clauses with closing streams/connections

Incomplete content (buffer) of webpage

I want to read the content of a webpage with the following methods, but I only get 60-70 percent of it.
I've tried 2 different methods to read the webpage, both with the same result. I also tried different Urls. I get no errors or timeouts.
What I am doing wrong ?
URL url = new URL(uri.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try
{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
this.content = sb.toString();
}
finally
{
urlConnection.disconnect();
}
AND
HttpGet get = new HttpGet(uri);
HttpClient defaultHttp = new DefaultHttpClient(httpParameters);
HttpResponse response = defaultHttp.execute(get);
StatusLine status = response.getStatusLine();
if(status.getStatusCode() == HttpStatus.SC_OK)
{
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
String encoding = "utf-8";
//long length = entity.getContentLength();
//if(entity.getContentEncoding() != null)
//{
// encoding = entity.getContentEncoding().getValue();
//}
//if(length > 0)
//{
byte[] buffer = new byte[1024];
long read = 0;
do
{
read = stream.read(buffer);
if(read > 0)
{
this.content += new String(buffer, encoding);
}
}while(read > 0);
//}
}
#edit
I've tried it with C# and WinForms. I read the complete html source of that webpage.
With java-android it doesn't work.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.kicker.de");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();
reader.Close();
response.Close();
the httpurlconnection in apache's util jar has limited the biggest bytes in a response, i couldn't remember the number of it.
But in most of time ,may you use the http conncetion in UI thread , so sometimes it's not safe,and maybe will be killed, you can choose to deal with the http request in a thread but not the UI thread. So I want to know if you do it in the UT thread
I have currently the same Problem. I tried my Code in a simple Java Application and I receive the whole content. But on Android, the Content is incomplete. This Question is now a year old. I guess you have solved it in the meantime. Can you please add your Solution?
Edit:
I wrote the content into a File on my Android Device. The Content was complete!
It seems logcat doesn´t show the complete Output you receive from the Devie.

Categories

Resources