I have an android login app which post two parameters i.e username and password. These 2 parameters are passed as json. The problem is I m not able to call the .net web api. This api confirms the login details and response I get from the page is id = 0 message "null"
I dont know where i am going wrong.
The complete source code
package com.hmkcode.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are connected");
}
else{
tvIsConnected.setText("You are NOT connected");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject login = new JSONObject();
login.accumulate("Email", person.getName());
login.accumulate("Password", person.getCountry());
// 4. convert JSONObject to JSON to String
json = login.toString();
JSONObject finaldata = new JSONObject();
finaldata.put("LoginRequestTemp", json);
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(),
"Enter some data!",
Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute
("http://dev.blinkawards.com/blinkawards.RestService/Service1/LoginTemp");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(),result , Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString
(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader
( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
Related
I follow this post http://hmkcode.com/android-send-json-data-to-server/ and some functions is depreciated. I like to understand how I send an information to a web service.
I try to update the post but i got some mistake.. I know my code has some mistake My code is:
enter code here
package com.example.paulo.myapp.POST;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.paulo.myapp.R;
import com.facebook.internal.BundleJSONConverter;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Post_Dados extends AppCompatActivity implements View.OnClickListener {
TextView isconected;
EditText customer, pais, twitter;
Button btn_enviar;
String person, country, tw;
static Dados dados;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post__dados);
/* recupera as views */
isconected = (TextView) findViewById(R.id.conected);
customer = (EditText) findViewById(R.id.customer);
pais = (EditText) findViewById(R.id.pais);
twitter = (EditText) findViewById(R.id.twitter);
btn_enviar = (Button) findViewById(R.id.sendWS);
/* checa se está conectado */
if (isConnected()) {
isconected.setText("Conectado !!!!");
}
else {
isconected.setText("Não conectado!!!");
}
/* click do botão */
btn_enviar.setOnClickListener(this);
}
private boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager ) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if ( info != null && info.isConnected()){
return true;
}
else { return false; } }
#Override
public void onClick(View view) {
String c = customer.getText().toString();
String p = pais.getText().toString();
String t = twitter.getText().toString();
if ( c.equals("") || p.equals("") || t.equals("") )
{
Toast.makeText(getBaseContext(), "Preenche os campos os dados!", Toast.LENGTH_LONG).show();
}
else{
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
}
}
/*metodo de conexao */
private static String POST(String url, String person) throws IOException, JSONException {
InputStream inputStream = null;
String result = "";
try{
/* 1. cria o httpClient */
URL endWeb = new URL(url);
HttpURLConnection con = (HttpURLConnection) endWeb.openConnection();
// 2. configurando o POST
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setRequestProperty("Accept", "application/json");
//3. define enviar e receber
con.setDoOutput(true);
con.setDoInput(true);
//4.faz a conexao
con.connect();
//5. Objeto json
String json = " ";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name",dados.getNome());
jsonObject.accumulate("country", dados.getEmail());
jsonObject.accumulate("twitter", dados.getTwitter());
//6.connverte json to json string
json = jsonObject.toString();
// Escreve o objeto JSON usando o OutputStream da requisição:
OutputStream outputStream = con.getOutputStream();
outputStream.write(json.getBytes("UTF-8"));
}
catch (Exception e){
throw e;
}
return "ok";
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>{
String result;
#Override
protected String doInBackground(String... urls) {
dados = new Dados(person.toString(), country.toString(), tw.toString());
try {
result = POST(urls[0], person);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Dados enviados!", Toast.LENGTH_LONG).show();
}
}
}
I this url http://hmkcode.appspot.com/post-json/index.html is to check it´s ok.
I like a help to get it ok.
Unfortunately sending HTTP requests in Android is quite the pain without using 3rd party libraries. Fortunately retrofit is awesome and is very widely used. There are a lot tutorials for it, you might try this one for example.
I am trying to make an app where i am supposed to send data from the application to a web server.
So far i've been searching and not been able to find a working example, i've found some using asynctask which does not work, so any help is appreciated!
try below code :-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
etTwitter = (EditText) findViewById(R.id.etTwitter);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else if(etTwitter.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
see below link for more info :-
http://hmkcode.com/android-send-json-data-to-server/
http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89
Try this,
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class AdminLogin extends Activity {
EditText adminUN, adminPass;
CheckBox cb;
Button loginBtn;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
// Your IP address or your website complete address
String adminLoginURL = "http://192.168.1.1/admin_login.php";
ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_login);
loginBtn = (Button) findViewById(R.id.adminLogin);
adminUN = (EditText) findViewById(R.id.adminUName);
adminPass = (EditText) findViewById(R.id.adminPass);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Admin_Login().execute();
}
});
}
class Admin_Login extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(AdminLogin.this);
dialog.setMessage("Please Wait..!");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
protected String doInBackground(String... params) {
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
dialog.dismiss();
}
}
void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(adminLoginURL);
// add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", adminUN
.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password", adminPass
.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
boolean matches = response.startsWith("User Found");
if (matches) {
// Do something start an Activity or do anything you wanted
}
} else {
showAlert();
}
} catch (Exception e) {
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert() {
AdminLogin.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(
AdminLogin.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_exit, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Create an .xml file to get the username, password, and login button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_wall"
android:gravity="center_horizontal"
android:orientation="vertical" >
<EditText
android:id="#+id/adminUName"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="50dip"
android:hint="Username"
android:singleLine="true" />
<requestFocus />
<EditText
android:id="#+id/adminPass"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
<Button
android:id="#+id/adminLogin"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dip"
android:text="Login"
android:textColor="#0b84aa" />
</LinearLayout>
You must have PhpMyAdmin to try this in local system, if you have hosted server part then try use the following php code and run it.
adminLogin.php
<?php
$hostname_localhost ="";
$database_localhost ="";
$username_localhost ="";
$password_localhost ="";
# Make sure above fields are filled with your config values (must)
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
if (empty($_POST['username'])) {
echo "Please Enter a name";
} else {
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
echo "Please Enter Your Password ";
} else {
$password = SHA1($_POST['password']);
}
$query_search = "select * from adminregister where username = '".$username."' AND password = '".$password."'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "\nNo Such User Found";
}
else {
echo "User Found";
}
mysql_close();
?>
Note: You need to create database and table specified in mysql to feed and retrieve the data
If any errors please leave a comment.
I am new to android development and am trying to work with json data. I followed the web page "
http://hmkcode.com/android-parsing-json-data/" to make a simple app to get and display json. It works fine with the tutorial json web site. But when I change the url to point to my website I get an exception error on the line "JSONObject json = new JSONObject(result);"
03-15 08:56:10.518: W/System.err(1330): org.json.JSONException: Value <?xml of type
java.lang.String cannot be converted to JSONObject
03-15 08:56:10.528: W/System.err(1330): at org.json.JSON.typeMismatch(JSON.java:111)
03-15 08:56:10.528: W/System.err(1330): at org.json.JSONObject.<init>(JSONObject.java:159)
03-15 08:56:10.528: W/System.err(1330): at org.json.JSONObject.<init>(JSONObject.java:172)
When I display the string I get it looks like this (almost, I had trouble formatting, the mgmtresponse line is all one line, I also blocked out the ip address):
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<mgmtResponse
responseType="operation"requestUrl="https://128.205.x.xxx/webacs/api/v1/op/info/version"
rootUrl="https://128.205.x.xx/webacs/api/v1/op">
-<versionInfoDTO>
<result>2.0.0.0.294</result>
</versionInfoDTO>
</mgmtResponse>
Here is the main section of code. As you can see I tried a bunch of things and commented out a bunch of things to get down to the problem. I am stuck at the point where I can not take my input and convert it to a json object. I think I need to format the response some how but I just can not figure out what is wrong.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Base64;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText etResponse;
TextView tvIsConnected;
static TextView response_code;
static String httpcode;
static String version;
#Override
// oncreate is called when activity is created
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
response_code = (TextView) findViewById(R.id.response_code);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("network is connected");
}
else{
tvIsConnected.setText("network is NOT connected");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("https://128.205.x.xx/webacs/api/v1/op/info/version");
// new HttpAsyncTask().execute("https://hmkcode.appspot.com/rest/controller/get.json");
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new MyHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("Authorization", "Basic " + Base64.encodeToString
("username:password".getBytes(), Base64.NO_WRAP));
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(request);
final int StatusCode = httpResponse.getStatusLine().getStatusCode();
String st=String.valueOf(StatusCode);
httpcode = st;
//HttpResponse httpResponse = HttpClient.execute(new HttpGet(url));
// receive response as inputStream
//HttpEntity entity = httpResponse.getEntity();
//result = EntityUtils.toString(entity);
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader
(inputStream,"iso-8859-1"),8);
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line+"\n";
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService
(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
// displays results to Edittext and displays recieved to toast
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
response_code.setText(httpcode);
try {
//etResponse.setText(result);
JSONObject json = new JSONObject(result);
//etResponse.setText(json.toString(1));
//JSONObject mgmtResponse =
// new JSONObject(json.getString("mgmtResponse"));
//JSONObject versionInfoDTO =
// new JSONObject(mgmtResponse.getString("versionInfoDTO"));
version = "NCS-Version";
//
//JSONArray articles = json.getJSONArray("articleList"); //get articles array
//str += "articles length = "+json.getJSONArray("articleList").length();
//str += "\n--------\n";
//str += "names: "+articles.getJSONObject(0).names(); //get first articles keys
//str += "\n--------\n";
//str += "url: "+articles.getJSONObject(0).getString("url"); //return an article url
//String str = "NCS Version";
//version += versionInfoDTO.getJSONObject("result");
etResponse.setText(version);
// not - etResponse.setText(json.toString(1));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//etResponse.setText(version);
}
}
}
As Rashmi points out, you are receiving data in XML-format, and attempting to parse it as JSON-format, which is giving you an error. The format of the data can usually be specified in the request URL.
EDIT
Your are using the URL https://128.205.x.xx/webacs/api/v1/op/info/version and I don't know what that is, if it's your own server or not, but usually, APIs provide both XML and JSON formats, which could look something like this:
https://example.com:2087/xml-api/functionname
for XML and
https://example.com:2087/json-api/functionname
for JSON
Some webservices will allow/require you to specify "application/json" as the accept header, so in addition to this:
HttpGet request = new HttpGet(url);
request.setHeader("Authorization", "Basic " + Base64.encodeToString
("username:password".getBytes(), Base64.NO_WRAP));
Say what you want back:
request.setHeader("Accept", "application/json");
And, if required, what you are supplying:
request.setHeader("Content-type", "application/json");
i have an android program having two fields name and pas which post the data in json format and the response is "data sent." instead of that response i want the name and pass parameters to be checked by my api which is connected to database.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data sent!", Toast.LENGTH_LONG).show();
}
the complete code
package com.hmkcode.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("Email", person.getName());
jsonObject.accumulate("Password", person.getCountry());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://dev.blinkawards.com/blinkawards.RestService/Service1/LoginRequestTemp");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
When I try to connect my app to MySQL database the application abruptly stops. I think the problem is with the jasonparsor class which I wrote. I need to accept the filed without posting any thing. how should I change my classes..
my JasonParsor is given below
package com.mahavega.qcdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
my activity which I want to display the data is
package com.mahavega.qcdemo;
import java.util.ArrayList;
import java.util.List;
import com.mahavega.qcdemo.R;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends Activity implements OnClickListener {
JSONParser jsonParser = new JSONParser();
private static final String url_product_detials = "http://neogdgt.com/mob/get_det.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_EVENT = "event";
private static final String TAG_EVENTITLE = "event_title";
private static final String TAG_EVENTDET = "event_details";
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
// Condetect cd = new Condetect(getApplicationContext());
// Boolean isInternetPresent = cd.isConnectingToInternet();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gestureDetector = new GestureDetector(this, new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
new GetEventDetails().execute();
ImageView ad = (ImageView) findViewById(R.id.imageView1);
ImageView im2 = (ImageView) findViewById(R.id.imageView2);
ImageView im3 = (ImageView) findViewById(R.id.imageView3);
ImageView im4 = (ImageView) findViewById(R.id.imageView4);
ImageView im5 = (ImageView) findViewById(R.id.imageView5);
ad.setOnClickListener(MainActivity.this);
im2.setOnTouchListener(gestureListener);
im2.setOnClickListener(MainActivity.this);
im3.setOnTouchListener(gestureListener);
im3.setOnClickListener(MainActivity.this);
im4.setOnTouchListener(gestureListener);
im4.setOnClickListener(MainActivity.this);
im5.setOnTouchListener(gestureListener);
im5.setOnClickListener(MainActivity.this);
ad.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boolean inet = isOnline();
if (inet)
{
startActivity(new Intent(MainActivity.this, Adds.class));
overridePendingTransition(R.anim.slide_left, R.anim.slide_right);
finish();
}
else {
displayAlert();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class MyGestureDetector extends SimpleOnGestureListener {
#Override
public boolean onFling (MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
{
float sensitvity = 50;
if((e1.getX() - e2.getX()) < sensitvity){
startActivity(new Intent(MainActivity.this, Login.class));
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
finish();
}
else if((e2.getX() - e1.getX()) > sensitvity){
startActivity(new Intent(MainActivity.this, Login.class));
overridePendingTransition(R.anim.slide_right, R.anim.slide_left);
finish(); }
return super.onFling(e1, e2, velocityX, velocityY);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ( keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
onBackPressed();
}
return true;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public void displayAlert()
{
new AlertDialog.Builder(this).setMessage("Please Check Your Internet Connection and Try Again")
.setTitle("Network Error")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
}
})
.show();
}
class GetEventDetails extends AsyncTask<String, String, String> {
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
String pid="1";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray eventObj = json
.getJSONArray(TAG_EVENT); // JSON Array
// get first product object from JSON Array
JSONObject event = eventObj.getJSONObject(0);
// product with this pid found
TextView txtEventname=(TextView) findViewById(R.id.textView2);
TextView txtEventdet=(TextView) findViewById(R.id.textView3);
// Edit Text
txtEventname.setText(event.getString(TAG_EVENTITLE));
txtEventdet.setText(event.getString(TAG_EVENTDET));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
}
}
and my getdetails.php class is
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
// get a product from products table
$result = mysql_query("SELECT *FROM tb_event_details WHERE event_id=1");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$events = array();
$events["event_id"] = $result["event_id"];
$events["event_title"] = $result["event_title"];
$events["event_details"] = $result["event_details"];
// success
$response["success"] = 1;
// user node
$response["events"] = array();
array_push($response["events"], $events);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No event found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No event found";
// echo no users JSON
echo json_encode($response);
}
?>
just add
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()