here is my java code and it makes an http request and send json object to php script.
login.java
String username = jTextField1.getText();
String password = jPasswordField1.getText();
JSONObject obj = new JSONObject();
obj.put("username", username);
obj.put("password", password);
//JSONArray list = new JSONArray();
//list.add(username);
//list.add(password);
//obj.put("logindata", list);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
HttpPost httppost = new HttpPost("http://localhost/kolitha/json_test/index.php");
StringEntity se = new StringEntity("myjson" + obj.toString());
httppost.setEntity(se);
System.out.print(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
System.out.println(obj.toString());
//response = httpclient.execute(httppost);
HttpGet httpget = new HttpGet("http://localhost/kolitha/json_test/index.php");
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity));
} catch (Exception e) {
e.printStackTrace();
System.out.print("Cannot establish connection!");
}
this is my index.php script and i am unable to extract username and password from the json object.
index.php
$obj = json_decode(file_get_contents('php://input'));
$username=$obj->{'username'};
$password=$obj->{'password'};
$connect=mysql_connect('localhost', 'root', '');
IF (!$connect){
die ('Failed Connecting to Database: ' . mysql_error());}
$d = mysql_select_db("kolitha_json_test");
if(!$d){ echo "db not selected";}
$sql="SELECT * FROM login WHERE username='$username' AND password='$password' ";
$result=mysql_query($sql) or die (mysql_error());
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
echo "true";
}
else
{
echo "false";
}
?>
Ok i left a comment but no one seems to pay attention to a comment. The error is in the Java Code
StringEntity se = new StringEntity("myjson" + obj.toString());
which adds a prefix to the json string called myjson
Why are Using both HttpPost and HttpGet. You are adding string entity to HttpPost request and not using it..
whereas you are using Httpget where you have not set ur username and password(so obviously there is no json data associated with httpget request)
Make changes here
response = httpclient.execute(httppost);//don comment this line
Add comment hereif you are using httppost
//HttpGet httpget = new HttpGet("http://localhost/kolitha/json_test/index.php");
//response = httpclient.execute(httpget);
Related
I want to create a swing application and refer to the database using json.I tried but it did not work and i'm new to json.I want to access the database using webservice.
Below my code.
Login.java
String username=jTextField1.getText();
String password=jPasswordField1.getText();
JSONObject obj = new JSONObject();
obj.put("username", username);
obj.put("password", password);
try {
HttpClient httpclient= new DefaultHttpClient();
HttpResponse response;
HttpPost httppost= new HttpPost("http://localhost/kolitha/json_test/index.php");
StringEntity se=new StringEntity ("myjson: "+obj.toString());
httppost.setEntity(se);
System.out.print(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
response=httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("result is "+responseBody);
}
catch (Exception e) {
e.printStackTrace();
System.out.print("Cannot establish connection!");
}
index.php
here is my php file and i want to get the json object and parse username and password to query and send the response java application.
<?php
$json = file_get_contents('php://input',0,null,null);
$json_output = json_decode($json);
$username;
$password;
foreach($json_output -> details as $detail)
{
$username = $detail -> username;
$password = $detail -> password;
}
$login_result = false;
$connect = mysql_connect('localhost', 'root', '');
IF(!$connect)
{
die('Failed Connecting to Database: '.mysql_error());
}
$d = mysql_select_db("kolitha_json_test");
if (!$d)
{
echo "db not selected";
}
$sql = "SELECT * FROM login WHERE username='$username' AND password='$password' ";
$result = mysql_query($sql) or die (mysql_error());
if (!$result){
$login_result = false;
return $login_result;
die("Could not run the Query ".mysql_error());
} else {
$login_result = true;
return $login_result;
}
?>
try adding
request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
And check if the response has an entity
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String responseBody = RestClient.convertStreamToString(instream);
System.out.println("result is "+responseBody);
}
My web service code is following i am using WCF Restful webservices,
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Login?parameter={parameter}")]
string Login(string parameter);
public string Login(string parameter)
{
/*
* input := {"username":"kevin","password":"123demo"}
* output:= 1=sucess,0=fail
*
*/
//Getting Parameters from Json
JObject jo = JObject.Parse(parameter);
string username = (string)jo["username"];
string password = (string)jo["password"];
return ""+username;
}
my client side(Android) code is following
JSONObject json = new JSONObject();
try {
json.put("username","demo");
json.put("password","password123");
HttpPost postMethod = new HttpPost(SERVICE_URI);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
nameValuePairs.add(new BasicNameValuePair("parameter",""+json.toString()));
HttpClient hc = new DefaultHttpClient();
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Exception", ""+e);
}
I am getting following output after calling Web service:
The server encountered an error processing the request. See server
logs for more details.
Basically my problem is I am unable to pass value by using NameValuePair.
Following code worked for me:
public static String getJsonData(String webServiceName,String parameter)
{
try
{
String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
final String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
}
return string;
}
I've tried several things but my android app is not sending post parameters. I run the app on a virtual device. This is the code:
#Override
public void run() {
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
obj.put("username", "abcd");
obj.put("password", "1234");
post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
BufferedReader reader = new BufferedReader(isr);
String line = "";
while((line = reader.readLine()) != null){
System.out.println(line);
}
}catch(Exception e){
e.printStackTrace();
}
}
It should send a post request to a PHP page. This page displays the output of the POST array:
<?php
print_r($_POST);
?>
When I run the app, it displays an empty array.
thats because you're sending JSON
standard php $_POST is build from key-value pairs
so you should post key1=value1&key2=value2
or you should read from
$HTTP_RAW_POST_DATA
or
<?php $postdata = file_get_contents("php://input"); ?>
and use
json_decode( $postdata );
PHP will not automatically decode json for you
you can also use another approach and POST your json like data=YourJsonCode
and then decode it using json_decode( $_POST['data'] );
Try sending url encoded name/value pairs. You can also use EntityUtils to convert the response to a String for you.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(page);
HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
post.setHeader("Content-Type","application/x-www-form-urlencoded");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("username", "abcd"));
formParams.add(new BasicNameValuePair("password", "1234"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse httpResponse = client.execute(post);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
Problem solved. There was a htaccess file that redirected all non www pages.
For example if we need to send content which is in this format , how do we do it
{"name1":[{"name11":"value11"},{"name11":"value12"},{"name11":"value13"}],"name2":value2}
I know how to set the basic kind
{"name1":"value1","name2":value2}
NameValuePair[] nameValuePairs = new NameValuePair[2];
nameValuePairs[0]= new BasicNameValuePair("name1", "value1");
nameValuePairs[1] = new BasicNameValuePair("name2", value2);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
How can we achieve nesting
Please see this question as it has a couple of answers that should help you. Here is a brief snippet from the answers code:
HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);
The other answer says you can do something like this:
protected void sendJson(final String email, final String pwd) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost(URL);
json.put("email", email);
json.put("password", pwd);
StringEntity se = new StringEntity( "JSON: " + json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
catch(Exception e){
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}
}
I'm trying to submit some data formatted as a JSONObject to a web server. My understanding was that this is done with an httpclient on android and then a php file on the server. If that's not the case stop here and correct me, otherwise here's how i'm trying to send the data:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myhost/data.php");
try {
String UN = username.getText().toString();
String PW = password.getText().toString();
String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\": \""+PW+"\"}}";
JSONDATA = new JSONObject(jString);
//JSONDATA = new JSONObject();
//JSONDATA.put("username", UN);
//JSONDATA.put("password", PW);
should i be using: httppost.setEntity(new UrlEncodedFormEntity(JSONDATA));
or should i be doing it like so:
StringEntity se = new StringEntity(JSONDATA.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
HttpEntity entity;
entity = se;
httppost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httppost);
The question really is how are you planning to pull the data out on the server? What does your PHP look like? What may be easiest is to just pass the JSON as a parameter:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myhost/data.php");
try {
String UN = username.getText().toString();
String PW = password.getText().toString();
String jString = "{\"login\": { \"username\": \""+UN + "\",\"password\":\""+PW+"\"}}";
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("value", jString));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response;
response = httpclient.execute(httppost);
and then on the server side you can just do
<?php
$obj = json_decode($_POST['value']);
to retrieve it.