How to I send POST parameters in this android studio code [duplicate] - android

This question already has answers here:
Sending POST data in Android
(17 answers)
Closed 5 years ago.
I'm new to android and learning it now. I'm working on an application where I was able to get response form a get request successfully. Now I want to execute a POST request with a single parameter this is what I've came up with so far:
public class BGTask extends AsyncTask<String, String, String > {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
String color = "null";
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
//I want to pass the id parameter
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
int status = parentObject.getInt("status");
if(status == 1) {
color = parentObject.getString("bgcolor");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return color;
}
}
The variable color is in hex code i.e #FF0089

** Use volley library for GET , POST and network calls it's very simple and efficient **
First create AppController.java
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
Second make POST request
public void Send() {
final String First = "";
final String Second = "";
StringRequest stringRequest = new StringRequest(Request.Method.POST, CREATEORDER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
JSONObject jObj = null;
try {
jObj = new JSONObject(response);
String success = jObj.getString("success");
String errorMessage = jObj.getString("message");
if (success.equals("")) {
Intent intent = new Intent(SendGiftActivity.this, PayScreenActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(SendGiftActivity.this, errorMessage, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
// Toast.makeText(SignUpActivity.this, response, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SendGiftActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_FIRST_PARAMETERS, First);
params.put(KEY_SECOND_PARAMETER, Second);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Include volley library
compile 'com.android.volley:volley:1.0.0'
Don't forget to add android:name=".AppController" in application tag of manifest file

Related

How can i get Instagram json data on Android?

I want to use Instagram data in my Android app without using API. I am having trouble because I haven't worked with .json and volley library before. With the link below, we can get the data of Instagram user as json.
Get Json Datas On Instagram:
https://www.instagram.com/android/?__a=1
I want to take this data as json in the Android application and take the username as an example. I tried a lot of things but I didn't get an answer. It gives errors and does not return any results. The reason I got the error is that I need to break up the data in two sets so that I can pull the data I want to get. So I couldn't find an answer and didn't get the username. I would be glad if you help. I'm sorry for my bad english. If what I wrote is incomprehensible, please refer to the codes and screenshot. You will definitely understand.
My Activity;
public class MainActivity extends AppCompatActivity {
private Button Find_Button;
private TextView Find_Textview;
private String urlJsonArry = "https://www.instagram.com/android/?__a=1";
String data = "";
private ProgressDialog pDialog;
private String jsonResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
Find_Button = findViewById(R.id.button_login_01);
Find_Textview = findViewById(R.id.textview_login_01);
Find_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeJsonArrayRequest();
}
});
}
private void makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(urlJsonArry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("result", response.toString());
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
JSONObject phone = person
.getJSONObject("graphql");
String name = phone.getString("username");
jsonResponse += "userName: " + name + "\n\n";
}
Find_Textview.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("errorTAG", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
> AppController.class;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
The json given by Insta is starting from JSONobject not JSONArray. Please make the following corrections in your code.
Updated
private void makeJsonArrayRequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
urlJsonArry,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Do something with response
//mTextView.setText(response.toString());
// Process the JSON
jsonResponse = "";
try{
// Get the JSON array
JSONObject person = response;
JSONObject graphqlObject = person
.getJSONObject("graphql");
JSONObject userObject = person
.getJSONObject("user");
String name = userObject.getString("username");
jsonResponse += "userName: " + name + "\n\n";
Find_Textview.setText(jsonResponse);
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}

jsonexception value <br of type java.lang.string cannot be converted to jsonarray

i need to show post of user .. i make recyclerview
and php file when you pass a user_id you get your post in RecyclerView ..
For testing i made php file get all posts of users and worked successfully,
but when i make php file when you are passing a user_id it worked on post man and get result as array postman result
its the same result of first php file that get all posts
but in android php file one get result and show it in recyclerview with no problem
with seconed php file give me a message "jsonexception value
thats my java code
private void load(){
final String user_id=SharedPref.getInstance(getActivity()).getid();
RequestQueue rq= Volley.newRequestQueue(getActivity());
JsonArrayRequest jar=new JsonArrayRequest(Request.Method.POST, Constants.MyPOST_URL,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int x=0;x<response.length();x++)
{
try {
JSONObject obj=response.getJSONObject(x);
location=obj.getString("location");
description=obj.getString("description");
bloodtype=obj.getString("bloodtype");
number=obj.getString("number");
date=obj.getString("created_at");
GetMyPost data=new GetMyPost(description,location,bloodtype,number,date);
data_list.add(data);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter = new RecyclerViewAdapter(getActivity(),data_list);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),error.getMessage(),Toast.LENGTH_LONG).show();
}
}
)
{
#Override
protected Map<String,String> getParams() {
Map<String,String> params = new HashMap<String, String>();
params.put("user_id",user_id);
return params;
}
};
rq.add(jar);
}
i get user_id from sharedpref i tested it and return my id with no problem
please help me
send params to server
Map<String, String> params = new HashMap<String, String>();
try {
params.put("user_id", user_id);
JSONObject JsonObj = new JSONObject(params);
JsonArrayRequest jar=new JsonArrayRequest
(Request.Method.POST,
Constants.MyPOST_URL ,
JsonObj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
getData_and_set_Model(response);
}catch (Exception ex){
ex.printStackTrace();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(productActivity.this,"VolleyError : " +
error.getMessage()+ "", Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectReq);
}catch (Exception ex){}
and
create class AppController extends Application
in AndroidManifest >
> <application
> android:name=".AppController"
>
> <uses-permission android:name="android.permission.INTERNET" />
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
you problem is send server
Tell me if it is not resolved

Passing parameters in Volley JSONArray Request

I am trying to get posts from server based on a parameter i.e. email address. How do I send parameters in JSONArrayRequest so that only those posts are retrieved which are matched with the given parameter? Here is my code:
JsonArrayRequest:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i= 0; i<response.length(); i++){
try {
JSONObject object = response.getJSONObject(i);
Post post = new Post();
post.setContent(object.getString("Content"));
post.setDate(object.getString("PostDate"));
post.setTime(object.getString("PostTime"));
postArray.add(post);
PostList.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getmInstance().addToRequestQueue(jsonArrayRequest);
And this is the AppController.Java class:
public class AppController extends Application {
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
public static final String TAG = AppController.class.getSimpleName();
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getmInstance() {
return mInstance;
}
public RequestQueue getmRequestQueue()
{
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getmImageLoader(){
getmRequestQueue();
if(mImageLoader == null){
mImageLoader = new ImageLoader(this.mRequestQueue, new BitmapCache());
}
return mImageLoader;
}
public <T> void addToRequestQueue(Request<T> request, String tag ){
request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getmRequestQueue(). add(request);
}
public <T> void addToRequestQueue(Request<T> request ){
request.setTag(TAG);
getmRequestQueue(). add(request);
}
public void cancelPendingRequest(Object tag){
if(mRequestQueue != null){
mRequestQueue.cancelAll(tag);
}
}
}
void MakePostRequest() {
StringRequest postRequest = new StringRequest(Request.Method.POST, EndPoints.BASE_URL_ADS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
value1= jsonResponse.getString("Your ID1");
value2= jsonResponse.getString("Your ID2");
} catch (JSONException e) {
e.printStackTrace();
banner_id = null;
full_id = null;
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
value1= null;
value2= null;
}
}
) {
// here is params will add to your url using post method
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("app", getString(R.string.app_name));
//params.put("2ndParamName","valueoF2ndParam");
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
}
this post request is using this compile 'com.mcxiaoke.volley:library:1.0.19' volley version.
i am just adding app name as parameter.you can add more params.

Volley JsonObjectRequest sending 3 JSONObject in same request?

I created a JsonObjectRequest that I use to send a JSONObject to my WebService. When I try send this JSONObject the object is sending but send 3 objects instead 1. Looking in my data base there's 3 objects added.
I can't understand why this problem, because I always send 1 JSONObject but in webservice there's 3 objects.
I tried to use Postman of Google Chrome, and using Postman send 1 JSONObject normally.
What can be ?
JsonObjectRequest
public JsonObjectRequest sendContatoToEmpresa(String nome,
String email,
String telefone,
String assunto,
String mensagem,
String idEmpresa,
final ContatoAdapter listener){
urlPost.append(WebServiceURL.getBaseWebServiceURL());
urlPost.append("/ws/contatos/contatos/add.json");
JSONObject jsObject = new JSONObject();
try {
JSONObject objs = new JSONObject();
objs.put("nome", nome);
objs.put("email", email);
objs.put("telefone", telefone);
objs.put("assunto", assunto);
objs.put("mensagem", mensagem);
objs.put("pessoa_id", idEmpresa);
jsObject.put("Contato", objs);
Log.i("JSONOBJECT->", jsObject.toString());
}catch(JSONException e){
Log.e("JSONException->", e.getLocalizedMessage());
}
Log.i("URL CONTATO EMPRESA->", urlPost.toString());
JsonObjectRequest apc = new JsonObjectRequest(Request.Method.POST,
urlPost.toString(),
jsObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
try {
Log.i("JSOBJECT->", jsonObject.toString());
if(jsonObject.getString("status").equals("999")){
listener.isSend(true);
}else{
listener.isSend(false);
}
} catch (JSONException e) {
Log.e("JSONException->", e.getLocalizedMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("ERROR METHOD:", "sendContatoToEmpresa in ContatoDAO: " + volleyError.getLocalizedMessage());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
String auth = new String(android.util.Base64.encode((BasicAuthenticationRest.USERNAME + ":" + BasicAuthenticationRest.PASSWORD).getBytes(), android.util.Base64.URL_SAFE | android.util.Base64.NO_WRAP));
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Authorization", "Basic " + auth);
return headers;
}
};
return apc;
}
Activity
public Integer sendContatoToEmpresa(String nome,
String email,
String telefone,
String assunto,
String mensagem,
String idEmpresa){
final int[] send = {0};
if(nome.length() == 0 ||
email.length() == 0 ||
telefone.length() == 0 ||
assunto.length() == 0 ||
mensagem.length() == 0){
Toast.makeText(getView().getContext(), "Informe todos os campos", Toast.LENGTH_SHORT).show();
send[0] = 0;
}else{
final ProgressDialog progress = new CustomProgressDialog().getCustomProgress(null, getView().getContext());
progress.show();
JsonObjectRequest app = new ContatoDAO().sendContatoToEmpresa(nome,
email,
telefone,
assunto,
mensagem,
idEmpresa,
new ContatoAdapter(){
#Override
public void isSend(Boolean value) {
if(value){
send[0] = 1;
}
progress.dismiss();
}
});
CustomVolleySingleton.getInstance(getView().getContext()).addToRequestQueue(app);
}
return send[0];
}
CustomVolleySingleton
public class CustomVolleySingleton extends Application{
private static CustomVolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
public static final String TAG = "VolleyPatterns";
private CustomVolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Try to do the following:
app.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Here you can change the timeout (MY_SOCKET_TIMEOUT_MS) and change the number of attempts (DefaultRetryPolicy.DEFAULT_MAX_RETRIES)

Creating an AsyncTask to work with 3 layers?

In my project I am use 3 layers: Activity, DAO and Web Service Transaction, layer Web Service Transaction has HttpClient to execute Get and Post in my web service.
An example to understand:
//structure
send: Activity->DAO->WebService
response: WebService->DAO->Activity
These works, but I'm using Threads and I don't want to use anymore threads. I want knows if there any way to create a generic AsyncTask that can return Boolean and List ?
Looking for a solution I founded this: Want to create a Generic AsyncTask but doesn't work to me, or I can't understand how this works.
How can I do to AsyncTask works in 3 layers as my project ?
So, here my real structure;
Activity
public class MainActivity extends ActionBarActivity {
private EditText login, senha;
private Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(android.os.Build.VERSION.SDK_INT > 9){
StrictMode.ThreadPolicy pol = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(pol);
}
login = (EditText)findViewById(R.id.usuario);
senha = (EditText)findViewById(R.id.senha);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//invoke methods of UsuarioDAO
}
});
}
}
DAO
public class UsuarioDAO{
private HttpClientTransaction httpClient;
/** constructor */
public UsuarioDAO() {
httpClient = new HttpClientTransaction();
}
/** insert new object */
public Boolean insert(Usuario u){
boolean insert = false;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "add"));
nameValuePairs.add(new BasicNameValuePair("nome", u.getNome()));
nameValuePairs.add(new BasicNameValuePair("login", u.getLogin()));
nameValuePairs.add(new BasicNameValuePair("senha", u.getSenha()));
String s = "http://192.168.1.102/android/login.php";
String response = httpClient.post(nameValuePairs, s);
try {
JSONObject obj = new JSONObject(response);
if(obj.getString("erro").equals("1")){
insert = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return insert;
}
/** check if usuario has login */
public Boolean isLogin(Usuario u){
boolean login = false;
String s = "http://192.168.1.102/android/login.php?action=get&login=paiva&senha=123";
String response = httpClient.get(s);
try {
JSONObject obj = new JSONObject(response);
if(obj.getString("erro").equals("1")){
login = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return login;
}
/** return a list with all usuarios */
public List<Usuario> getAllUsuario(){
List<Usuario> list = new ArrayList<Usuario>();
String s = "http://192.168.1.102/android/login.php?action=getAll";
String response = httpClient.get(s);
try {
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.getJSONArray("all");
for(int x = 0; x < jsArray.length(); x++){
JSONObject objArray = jsArray.getJSONObject(x);
Usuario u = new Usuario();
u.setNome(objArray.getString("nome"));
u.setLogin(objArray.getString("login"));
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
}
Web Service Transaction
public class HttpClientTransaction {
private static HttpClient httpClient;
public HttpClientTransaction() {
httpClient = HttpClientConnection.getHttpClient();
}
/** execute POST */
public String post(List<NameValuePair> list, String url){
String s = "";
try {
HttpPost httpPost = new HttpPost(url);
//httpPost.addHeader("Authorization", "Basic " + BasicAuthenticationRest.getBasicAuthentication());
httpPost.setEntity(new UrlEncodedFormEntity(list));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
s = EntityUtils.toString(entity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return s;
}
/** execute GET */
public String get(String url){
String s = "";
try {
//executa o get
HttpGet httpGet = new HttpGet(url);
//httpGet.addHeader("Authorization", "Basic " + BasicAuthenticationRest.getBasicAuthentication());
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if(entity != null){
s = EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
To my problem I resolved use Volley Library and now works.
I did this
Volley Singleton
public class CustomVolleySingleton extends Application{
private static CustomVolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
public static final String TAG = "VolleyPatterns";
private CustomVolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized CustomVolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Application Controller
public class ApplicationController extends Request<JSONObject>{
private Map<String, String> params;
private Response.Listener<JSONObject> listener;
//Construtores
public ApplicationController(String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = listener;
this.params = params;
}
public ApplicationController(int method, String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.params = params;
}
//método requerido.
protected Map<String, String> getParams() throws AuthFailureError {
return params;
};
//método requerido.
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
//método requerido
#Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
}
UsuarioDAO
public class UsuarioDAO{
private String url = "http://192.168.1.102/android/login.php?action=get&login=paiva&senha=123";
/** constructor */
public UsuarioDAO() {
}
public static ApplicationController isLogin(Usuario u, final UsuarioImp usuarioImp){
String s = "http://192.168.1.102/android/login.php?action=get&login=paiva&senha=123";
ApplicationController app = new ApplicationController(s,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject obj) {
try {
if(obj.getString("erro").equals("1")){
Usuario u = new Usuario();
u.setNome("Fernando Paiva - Logado");
usuarioImp.onLoginSuccess(u);
}else{
usuarioImp.onLoginFailure("Erro de login");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
//usuarioImp.onLoginFailure("erro de login");
}
});
return app;
}
Usuario Interface
public interface UsuarioImp {
public void onLoginSuccess(Usuario u);
public void onLoginFailure(String message);
}
Activity
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ApplicationController app = UsuarioDAO.isLogin(new Usuario(), new UsuarioImp() {
#Override
public void onLoginSuccess(Usuario u) {
Log.i("USUARIO NOME: ", u.getNome());
}
#Override
public void onLoginFailure(String message) {
Log.i("ERROOOO: ", message);
}
});
CustomVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(app);
CustomVolleySingleton.getInstance(getApplicationContext()).cancelPendingRequests(CustomVolleySingleton.TAG);
}
});

Categories

Resources