Sending variable to PHP server from Android - java

I'm having the hardest time, what I want is for my android application to send a STRING to my server, my server will then choose a function based upon what STRING was sent in PHP. Once the function is done, it will return a JSONObject. I don't want to use any Deprecated methods. I'm trying to implement the sending a STRING to the server to parse and use an appropriate function in PHP then send a JSON back to my android application. Can anyone please show some code from the android side?
So what I'm looking for is, help with the Android code to send a STRING to the server, then read the response from the server which will be a JSON.

For Android you can use HTTP Connection URL. An example is mentioned here How to add parameters to HttpURLConnection using POST
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "Chatura"));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
..
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
For PHP just accept a post request which is coming form Andrid as below
<?php
echo '{ "name" = "Hello ' . htmlspecialchars($_POST["name"]) . '"}';
?>

Related

Send http post request to URL with query string using HttpPost client in java

I need to send a post request to url which is formed as follows:
www.abc.com/service/postsomething?data={'name':'rikesh'}&id=45
Using HttpPost client in java, how can post request to such query strings
I could connect from javascript easily through ajax but from java client, it's failing.
(I know sending querystring in post request is stupid idea. Since I am connecting to someone else's server I cannot not change the way it is)
Here is one way to send JSON in a POST request using Java (without Apache libraries). You might find this helpful:
//init
String json = "{\"name\":\"rikesh\"}";
String requestString = "http://www.example.com/service/postsomething?id=45";
//send request
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
int responseCode = conn.getResponseCode();
//get result if there is one
if(responseCode == 200) //HTTP 200: Response OK
{
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while((output = br.readLine()) != null)
{
result += output;
}
System.out.println("Response message: " + result);
}

How to decode JSON from Java REST API request?

I'm sending data to an API from Java using POST.
What I'm trying to do is send a particular variable to the API in the POST request, and then use the value of it. But currently the value is empty. The API is definitely being called.
My Java looks like this:
String line;
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL("https://www.x.com/api.php");
String payload = "{\"variable1\":\"value1\",\"variable2\":\"value2\"}";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
}
This is based on: How to send Request payload to REST API in java?
Currently the value isn't being read correctly. Am I sending it correctly in Java? Do I have to do something to decode it?
The $_POST variable is not set for all HTTP POST requests, but only for specific types, e.g application/x-www-form-urlencoded.
Since you are posting a request containing JSON entity (application/json), you need to access it as follows.
$json = file_get_contents('php://input');
$entity= json_decode($json, TRUE);
You can try to use the following code instead of your String variable payload:
List<NameValuePair> payload = new ArrayList<NameValuePair>();
payload.add(new BasicNameValuePair("variable1", "value1");
That worked for me

error while sending data from java code to PHP in localhost using HTTPPost request

This is my java code to send data through HTTPPost request:
import java.io.*;
import java.net.*;
class HttpURLConnectionEx{
public static void main(String[] args) throws Exception{
URL targetURL = new URL("http://localhost/JAVA/post.php");
HttpURLConnection conn =(HttpURLConnection) targetURL.openConnection();
String body= "fName="+ URLEncoder.encode("value1","UTF-8")+"&lName=" + URLEncoder.encode("value2","UTF-8");
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "UTF-8");
conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
try
{
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(body);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = rd.readLine()) != null) {
System.out.println(line);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
This is my PHP code present in localhost:
<?php
$data = $_POST["fName"];
$dbc = mysqli_connect('localhost','root','root123','JAVA')
or die("error connecting to mysql server");
$query = "INSERT INTO insert_table(data) VALUES('".$data."')";
if($query){
echo "data inserted sucessfully";
}
$result = mysqli_query($dbc,$query) or die("error querying database");
?>
This is the output i 'm getting when i run it in commandline:
A flush after the write is required.
out.flush();
edit
Undefined index: fName
The php error is clear enough, isn't? The $_POST array doesn't contain your POST variables.
First I've checked on php side the content of the post with var_dump($_POST) and:
/* save the raw post to a file */
file_put_contents('/tmp/post.txt', file_get_contents('php://input'));
Both were empty, so I used wireshark to check the HTTP/POST content, it was done but with Content-Length: 0 and without body.
Few googles to something similar to your code and I noticed the flush that mean OutputStreamWriter is buffered and at the time of the post request the output could be not written (sent to the server) or only partially, a good reason for zero content-length.
At this point I think you don't need to use conn.setRequestProperty for "Content-Length", it should be updated according with your buffer content length.

HTTP POST request on Android

For the last two hours i've been trying to make a POST request to this page http://www.halebop.se/butik/byt_behall_nummer/ and tried to send numberToPort. However i get a bunch of cookies and a 302 moved temporarily back.
All i want to do is send the POST request with the number and get the final page back. On iOS, i do this using ASIHTTPRequest which handles the redirect and cookies.
iOS code:
NSString *halebopURLString = #"http://www.halebop.se/kontantkort/byt_behall_nummer/#";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:halebopURLString]];
[request setPostValue:halebopNumber forKey:#"numberToPort"];
[request setPostValue:#"continue" forKey:#"action"];
[request setPostValue:#"submit" forKey:#"submit"];
[request startSynchronous];
How do i do this on Android?
As an alternative, a PHP solution is acceptable.
Edit: Tried this, it gives no output and no exceptions. I have the internet permission. Expected result: Send POST, get 302 and cookies back, send cookies to URL from 302 and get HTML back (Checked with FireBug) however i get nothing.
try {
InputStream myInputStream =null;
URL url;
url = new URL("http://www.halebop.se/kontantkort/byt_behall_nummer/#");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write("numberToPort="+n+"&action=continue&submit=submit");
wr.flush();
myInputStream = conn.getInputStream();
wr.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(myInputStream), 4096);
String line;
StringBuilder sbResult = new StringBuilder();
while ((line = rd.readLine()) != null) {
sbResult.append(line);
Log.d(TAG, "Line "+line);
}
rd.close();
String contentOfMyInputStream = sbResult.toString();
Log.d(TAG, "Output "+contentOfMyInputStream);
} catch (Exception e) {
Log.d(TAG,e.getMessage());
}
Here is how you can set the post parameters:
HttpPost httpost = new HttpPost(LOGIN_URL);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("test1","test1" ));
nvps.add(new BasicNameValuePair("test2", "test2" ));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = getResponse(httpost);
Here is the detailed explanation about the code.
I also explained How to retrieve HTTP cookies from your response and set them into request here
If you are using HttpUrlConnection, then HttpUrlConnection#setFollowRedirects might be what you are after. Set it to true to make it automatically resolve the redirect. Even better to use setInstanceFollowRedirects(true) since blindly following redirects (what the static setFollowRedirects would cause) is frowned upon from a security perspective.

Preemptive Basic Auth with HttpUrlConnection?

What is the best way to use preemptive basic http authentication using HttpUrlConnection. (Assume for now I can't use HttpClient).
EDIT for clarification: I'm setting the un/pw correctly in the request header using Base64 encoding. Are there any additional flags or properties that need to be set, or is the fact that I'm setting the basic auth headers for the request all that is needed for preemptive basic auth?
If you are using Java 8 or later, java.util.Base64 is usable:
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
String encoded = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8)); //Java 8
connection.setRequestProperty("Authorization", "Basic "+encoded);
Then use the connection as normal.
If you're using Java 7 or lower, you'll need a method to encode a String to Base64, such as:
byte[] message = (username+":"+password).getBytes("UTF-8");
String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(message);
Yes, that's all you have to do in order to use Basic Auth. The code above to set the Request Property should be done immediately after opening the connection and before getting the Input or Output streams.
Incidentally, in case someone else runs into the same, the android problem, is also present if you use org.apache.commons.codec.binary.Base64 and do Base64.encodeBase64String(). You need to do Base64.encodeBase64() and get a byte[] then construct the string.
It caught me offguard entirely that the results would be different for the line ending between those two methods.
You can use java.net.Authenticator to configure basic auth. globally for every request send by your application, see :
http://docs.oracle.com/javase/7/docs/technotes/guides/net/http-auth.html
http://developer.android.com/reference/java/net/Authenticator.html#getPasswordAuthentication()
you need to do this just copy paste it be happy
HttpURLConnection urlConnection;
String url;
// String data = json;
String result = null;
try {
String username ="danish.hussain#gmail.com";
String password = "12345678";
String auth =new String(username + ":" + password);
byte[] data1 = auth.getBytes(UTF_8);
String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
//Connect
urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+base64);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
JSONObject obj = new JSONObject();
obj.put("MobileNumber", "+97333746934");
obj.put("EmailAddress", "danish.hussain#dhl.com");
obj.put("FirstName", "Danish");
obj.put("LastName", "Hussain");
obj.put("Country", "BH");
obj.put("Language", "EN");
String data = obj.toString();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
I was having this problem too.
And Now I have solved this problem.
My code is :
URL url = new URL(stringUrl);
String authStr = "MyAPIKey"+":"+"Password";
System.out.println("Original String is " + authStr);
// encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(authStr .getBytes());
String authEncoded = new String(bytesEncoded);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic "+authEncoded);
It may help many others.
Best of luck.
Regarding the Base64 encoding problem, I found this library: http://sourceforge.net/projects/migbase64/
I have not fully vetted it but I am using it for the Basic Authentication solution shown above (as well as for image encoding/decoding), and it works well. It provides a parameter for whether or not to include the newline.

Categories