HTTP Request POST JSON Object in Body - android

Hey guys I'm struggeling with HTTP Requests in Java/Android. I want to create a new Github issue. So I've looked it up, and almost everybody did it the same way, but I have the problem that AndroidStudio tells me, that all the classes (HttpClient, HttpPost, ResponseHandler) doesn't exist, did I something wrong or why I don't have them?
private class GithubPostIssues extends AsyncTask<String, Void, String> {
private View view;
public GithubPostIssues(View view) {
this.view = view;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(FeedbackActivity.this, "Feedback/Hilfe gesendet", Toast.LENGTH_SHORT).show();
finish();
}
#Override
protected String doInBackground(String... params) {
return addIssue(view);
}
private String addIssue(View view) {
//here I'm getting some values from the user input and pass them in to the execute method
return execute(title, body, bug, help, question, feature, enhancement, design);
}
private String execute (String title, String body, boolean bug,
boolean help, boolean question, boolean feature,
boolean enhancement, boolean design) {
//Building the JSONOBject to pass in to the Request Body
JSONObject issue = new JSONObject();
JSONArray labels = new JSONArray();
try {
issue.put("title", title);
issue.put("body", body);
labels.put("0 - Backlog");
if (bug) {
labels.put("bug");
}
if (help) {
labels.put("help");
}
if (question) {
labels.put("question");
}
if (feature) {
labels.put("feature");
}
if (enhancement) {
labels.put("enhancement");
}
if (design) {
labels.put("design");
}
issue.put("labels", labels);
return makeRequest("http://requestb.in/uwwzlwuw", issue);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private String makeRequest (String uri, JSONObject issue) {
//all these clases aren't found by Android Studio
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(issue));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
return httpClient.execute(httpPost, responseHandler);
}
}

Try adding this inside gradle:
android {
useLibrary 'org.apache.http.legacy'

Related

Showing values of multiple columns in database via android

I have an app that should send a the phone number and retrieve a value from the database, now I change the query and my code should retrieve values of multiple columns, So where changes should be in my code.
public class JSONTransmitter extends AsyncTask<JSONObject, Void, String>
{
HttpResponse response;
String url = "http://192.168.1.97:89/Derdeery/bankOsman.php";
private AsyncCallback asyncCallback;
public JSONTransmitter(Context context) {
// attach the callback to any context
asyncCallback = (AsyncCallback) context;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
asyncCallback.onResponse(result);
}
protected String doInBackground(JSONObject... data)
{
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
String resFromServer = "";
try {
StringEntity se = new StringEntity("json=" + json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
Log.i("Response from server", resFromServer);
} catch (Exception e) {
e.printStackTrace();
}
return resFromServer;
}
public static interface AsyncCallback {
void onResponse(String res);
}
}
Here is something to consider:
First, in your php code (server-side), query your data perhaps separately. So for instance, you can get those that match column A and then query for those that match column B.
Generate Json for each (A and B accordingly)
Then create a single JSON object that contains the two sets of data like this:
{
"DataFromColumnA" : {},
"DataFromColumnB" : {}
}
Once you have made your HTTP request in your android code, you can get the specific data by getting "DataFromColumnA" json Object and B respectively.
I hope this helps you get your problem solved!

NetworkOnMainThreadException

Trying to read and parse some json data in my app. I implemented Parser class extending AsyncTask as follows:
public class JSONParser extends AsyncTask<Void, Void, String> {
private String strUrl;
private List<NameValuePair> params;
private String result;
private String response;
public static final String RESULT_SUCCESS = "success";
public static final String RESULT_FAILED = "failed";
public JSONParser(String strUrl, List<NameValuePair> params) {
this.strUrl = strUrl;
this.params = params;
}
private void parse() {
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strUrl);
// Add parameters
if (params != null) {
httppost.setEntity(new UrlEncodedFormEntity(params));
}
// Execute HTTP Post Request
HttpResponse httpResponse = httpclient.execute(httppost);
// return by response
result = RESULT_SUCCESS;
this.response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (Exception e) {
result = RESULT_FAILED;
this.response = null;
e.printStackTrace();
}
}
#Override
public String doInBackground(Void... params) {
parse();
return response;
}
public String getResult() {
return result;
}
public String getResponse() {
return response;
}
}
It works well in later android versions, but unfortunately it throws NetworkOnMainThreadException in older versions.
I've searched and found that I should use Strict mode in my app, but performance of threads became very bad! when I click parse button it freezes!
can you help me with more better solution?
Call you class like this, it will solve your issue !!
new JSONParser().execute();

Integration of android app with backend

i am developing an android app which i have to integrate with backend(developed in java and spring). Which will be the best way to integrate either WebServices or through http(JSON)..?
Thanks in advance.
To get a JSON Response in Android/Java you need to do this:
Create a custom API Connector class
Declare a method that will return a JSON Array
Create a AsyncTask class (optional)
Decode JSONArray
1.
public class CustomAPIConnector {
public final String URL = "http://10.0.2.2/your-project-url/"; // 10.0.2.2 goes to computer localhost if you put localhost, it will go to the devices localhost which should not exist
2.
public JSONArray getUserInfo(String username, String password) {
HttpEntity httpEntity = null;
// Add your POST variables to receive on your backend
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL + "login.php"); // have split up URL and page so you can redirect to different links easier if the URL changes
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
} catch (IOException e) {
e.printStackTrace();
}
JSONArray jsonArray = null;
if(httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
return jsonArray;
}
}
3.
private class AvailableUser extends AsyncTask<ApiConnector,Boolean,JSONArray> {
#Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].availableUsername(etusername.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
checkAvailableUsername(jsonArray);
}
}
private class AvailableEmail extends AsyncTask<ApiConnector,Boolean,JSONArray> {
#Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].availableEmail(etemail.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
checkAvailableEmail(jsonArray);
}
}
4.
private void checkAvailableEmail(JSONArray jsonArray) {
String s = "";
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = null;
try {
json = new JSONObject();
json = jsonArray.getJSONObject(i);
if(!json.getString("count").isEmpty()) {
if(json.getString("count").equalsIgnoreCase("0")) {
status.setText("");
passedemail = true;
return;
} else {
status.setText("Email Taken");
passedemail = false;
return;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
status.setText("Failed - checkAvailableEmail");
}
}
Please note that this is actual code I have in one of my apps that registersa user, the getUserInfo gets all information from the user, and the Available email asynctask class is separate from the getUserInfo, it is the registering part, that checks if the email is available.
From here on, you can copy the code and change what you need to.
JSON as name says java script object notation would help you to exploit OOPS , POST/GET and js at backend .
I use JSON , its easy to code , parse and handle

Using AsyncTask with Fragments: Android

I have used AsyncTask with Activity, And it gave me desired result without any failure.
Now I need to use AsyncTask with Fragments. In Fragments AsyncTask is not updating UI. I got an answer here. I tried that logic in my code but still I'm not able to update UI after getting response from servlet. Your help will be very appreciated.
Code what I have tried:
public class FragmentMyProfile extends Fragment
{
TextView txtViewUserFullName;
SharedPreferences shrdPref;
String currentUserFirstName = "", currentUserEmail = "";
String URL = "http://10.0.2.2:8080/iGnite_Survey/GetUserDetailsServlet";
String jsonObjectReceivedFromServer = "";
public FragmentMyProfile()
{
// empty constructor required for fragment subclass
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_my_profile, container, false);
shrdPref = rootView.getContext().getSharedPreferences("shrdPref", Context.MODE_PRIVATE);
txtViewUserFullName = (TextView) rootView.findViewById(R.id.textViewUserFullName);
//get current user first name, default value is ""
currentUserFirstName = shrdPref.getString(String.valueOf(R.string.curentLoggedInUserFirstName), "");
currentUserEmail = shrdPref.getString(String.valueOf(R.string.curentLoggedInUserEmail), "");
//display current user first name
if(!currentUserFirstName.equals(""))
{
txtViewDisplayUserFirstName.setText("Welcome "+currentUserFirstName);
}
else
{
txtViewDisplayUserFirstName.setText(String.valueOf(R.string.welcomeUser));
}
//get all user details from server
GetUserDetailsAsyncTask getUserDetailsAsyncTask = new GetUserDetailsAsyncTask (new FragmentCallback()
{
#Override
public void onTaskDone(String output)
{
//txtViewUserFullName.setText(output);
}
});
getUserDetailsAsyncTask.execute(new String[] { URL });
return rootView;
}
public interface FragmentCallback
{
public void onTaskDone(String output);
}
//------------------------------------------------------------------------------
public class GetUserDetailsAsyncTask extends AsyncTask<String, Void, String>
{
private FragmentCallback mFragmentCallback;
public GetUserDetailsAsyncTask (FragmentCallback fragmentCallback)
{
mFragmentCallback = fragmentCallback;
}
#Override
protected String doInBackground(String... urls)
{
String output = null;
for (String url : urls)
{
output = sendDataToServer(url);
}
return output;
}
#Override
protected void onPostExecute (String output)
{
super.onPostExecute(output);
mFragmentCallback.onTaskDone();
txtViewUserFullName.setText("output");
}
private String sendDataToServer(String url)
{
String output = null;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_email", currentUserEmail));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
output = EntityUtils.toString(httpEntity);
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return output;
}
}
}
You have to use the inter-fragment communication concept to update the UI Thread from the fragment asynctask i.e INTERFACE
Please refer this tutorial with source code to understand it better : Handle Android AsyncTask Configuration Change Using Fragment

android http post asynctask

Please can anyone tell me how to make an http post to work in the background with AsyncTask and how to pass the parameters to the AsyncTask? All the examples that I found were not clear enough for me and they were about downloading a file.
I'm running this code in my main activity and my problem is when the code sends the info to the server the app slows down as if it is frozen for 2 to 3 sec's then it continues to work fine until the next send. This http post sends four variables to the server (book, libadd, and time) the fourth is fixed (name)
Thanks in advance
public void SticketFunction(double book, double libadd, long time){
Log.v("log_tag", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SticketFunction()");
//HttpClient
HttpClient nnSticket = new DefaultHttpClient();
//Response handler
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.books-something.com");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("book", book+""));
nameValuePairs.add(new BasicNameValuePair("libAss", libass+""));
nameValuePairs.add(new BasicNameValuePair("Time", time+""));
nameValuePairs.add(new BasicNameValuePair("name", "jack"));
//Encode and set entity
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//Execute
//manSticket.execute(postMethod);
String response =Sticket.execute(postMethod, res).replaceAll("<(.|\n)*?>","");
if (response.equals("Done")){
//Log.v("log_tag", "!!!!!!!!!!!!!!!!!! SticketFunction got a DONE!");
}
else Log.v("log_tag", "!!!!!!!?????????? SticketFunction Bad or no response: " + response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? SticketFunction Client Exception");
} catch (IOException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? IO Exception");
}
}
}
At first,
You put a class like following:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
interface Listener {
void onResult(String result);
}
private Listener mListener;
private HashMap<String, String> mData = null;// post data
/**
* constructor
*/
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
public void setListener(Listener listener) {
mListener = listener;
}
/**
* background
*/
#Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
// set up post data
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
}
return str;
}
/**
* on getting result
*/
#Override
protected void onPostExecute(String result) {
// something...
if (mListener != null) {
mListener.onResult(result)
}
}
}
Now.
You just write some lines like following:
HashMap<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");
data.put("key2", "value2");
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
#Override
public void onResult(String result) {
// do something, using return value from network
}
});
asyncHttpPost.execute("http://example.com");
First i would not recommend do a Http request in a AsyncTask, you better try a Service instead. Going back to the issue on how to pass parameter into an AsyncTask when you declared it you can defined each Object class of the AsyncTask like this.
public AsyncTask <Params,Progress,Result> {
}
so in your task you should go like this
public MyTask extends<String,Void,Void>{
public Void doInBackground(String... params){//those Params are String because it's declared like that
}
}
To use it, it's quite simple
new MyTask().execute("param1","param2","param3")

Categories

Resources