Since org.appache is deprecated in Android 5.1.1 , and they suggest to use HttpUrlConnection .
Could you help me to change my code this , with valid HttUrlConnection command (im new in Android)
package com.example.cbmedandroid;
import java.io.IOException;
import java.io.InputStream;
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.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://192.168.43.13:8000/api/horaire.json");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
Thanks
Also , getASCIIContentFromEntity(HttpEntity entity) seems to be deprecated to !
EDIT : This is what i have changed in my code .
protected String doInBackground(Void... params) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.43.13:8000/api/horaire.json");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
But what about the "LongRunningGetIO extends AsyncTask " method ?
a HttpGet request without setting anything (like an Accept: application/json header, choosing an encoding, ...) should be fairly equivalent to this:
#Override
protected String doInBackground(Void... params) {
return get("http://192.168.43.13:8000/api/horaire.json");
}
private String get(String urlString) {
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
Reader reader = new InputStreamReader(urlConnection.getInputStream());
try {
StringWriter writer = new StringWriter();
char[] cbuf = new char[8192];
int read;
while ((read = reader.read(cbuf)) != -1) {
writer.write(cbuf, 0, read);
}
return writer.toString();
} finally {
reader.close();
}
} catch (Exception e) {
return e.getMessage();
}
}
Try This
#Override
protected String doInBackground(Void... params) {
StringBuffer response_string = new StringBuffer();
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestMethod("POST");
OutputStream os = con.getOutputStream();
os.write(params.toString().getBytes("UTF-8"));
os.close();
int responseCode = con.getResponseCode();
System.out.println("PostParseURL "+url);
System.out.println("PostParseCODE " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response_string.append(inputLine);
}
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response_string.toString();
}
and yes there are no need to getASCIIContentFromEntity method and here params are the Your JSONObject request
Related
//[(START)File:ThirdActivity.java] -->
package com.example.caleb.splash_screen;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.OutputStream;
public class ThirdActivity extends AppCompatActivity {
//public String text = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt";
public TextView text;
private void writeStream(OutputStream out){
String output = "Hello world";
// out.write(output.getBytes());
//out.flush();
}
/*private String readStream(InputStream is) {
try {`enter code here`
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}*/
//[(START) readStream -->
private String readStream(InputStream in) throws IOException {
BufferedReader bin = new BufferedReader(new InputStreamReader(in));
//temporary
try {
StringBuilder sb = new StringBuilder();
String inputLine;
while ((inputLine = bin.readLine()) != null) {
sb.append(inputLine);
}
return sb.toString();
} finally {
}
}
//[(END) readStream -->
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third2);
text = (TextView)findViewById(R.id.textView);
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
}
}
//[(END)File:ThirdActivity] -->
//[(START)File:JSONTask] -->
package com.example.caleb.splash_screen;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Caleb on 12/17/2017.
*/
public class JSONTask extends AsyncTask<String,String,String> {
//final TextView txt = (TextView)findViewById(R.id.textView);
private Context context;
public JSONTask(Activity ThirdActivity) {
context = ThirdActivity;
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection urlConnection = null;
//{(START)] Working Connection:ALERT! Error within code will cause crash -->
try {
URL url = new URL(params[0]);
Log.w("testing", "test");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(false);
urlConnection.connect();
//urlConnection.setChunkedStreamingMode(0);
//OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
//writeStream(out);
/*int a = urlConnection.getResponseCode();
String b = String.valueOf(a);
Log.e(b, "yesssssssssssssssss");*/
InputStream in = urlConnection.getInputStream();
//InputStream in = new BufferedInputStream(urlConnection.getInputStream());
reader = new BufferedReader(new InputStreamReader(in));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
/*String data = readStream(in);
/*final TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("hello");
*/
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//{(END)] Working Connection -->
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
TextView text = (TextView) ((AppCompatActivity) context).findViewById(R.id.textView);
text.setText(result);
}
}
//[(END)File:JSONTask] -->
/Desired Effect/
Blockquote
I would like to pull data from the json file that the url points to and change the TextView within the UI called textView. I don't understand how to access the findviewbyid within the AsyncTask. I've looked all throughout the internet and couldn't find anything :( Any suggestions are greatly appreciated!!
try weak reference to get textview in asynctask
//call async task
new JSONTask(yourTextView).execute();
//in your async task
private final WeakReference<TextView> textViewReference;
public JSONTask (TextView textView){
textViewReference = new WeakReference<TextView>( textView);
}
#Override
protected void onPostExecute() {
TextView textView = textViewReference.get();
//set values to text view
}
I'm using OkHttp to do the same task in my apps
HTTP/2 support allows all requests to the same host to share a socket.
Connection pooling reduces request latency (if HTTP/2 isn’t available).
Transparent GZIP shrinks download sizes.
Response caching avoids the network completely for repeat requests.
Add this dependency
implementation 'com.squareup.okhttp3:okhttp:3.9.1'
Then create/code a new Class named OkHttpHandler
class OkHttpHandler extends AsyncTask<String, String, String> {
OkHttpClient client = new OkHttpClient();
private volatile String data;
public String getResult() {
return data;
}
#Override
protected String doInBackground(String... params) {
try {
Request.Builder builder = new Request.Builder();
builder.url(params[0]);
Request request = builder.build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
data = s;
}
}
}
and use it like this way
String str = new OkHttpHandler().execute("http://www.<TEST>.com/json").get();
I also suggest to check whether Wi-fi-Connected/Bluetooth-Connected or PhoneData-Enabled is false if true/else, Proceed to your code
hi every body i wrote a program to get data from server and show the data in list view with json
but when i start the app ,app immediately closed.
i checked my manifest and its okay , idont know what should i do , please help me!
Main Activity code:
package com.example.delta.travel;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends ListActivity {
private ProgressDialog pd;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> P;
JSONArray s=null;
private final String url="http://192.168.1.4/upload/travel.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new travel().execute();
}
class travel extends AsyncTask<String,String,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("login");
pd.show();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parms=new ArrayList<>();
JSONObject json=jParser.makeHTTPRequest(url,"GET",parms);
try {
int t=json.getInt("t");
if(t==1){
s=json.getJSONArray("travel");
for(int i=0;i<s.length();i++){
JSONObject c=s.getJSONObject(i);
String companyname=c.getString("companyname");
String cod=c.getString("cod");
String bign=c.getString("bign");
String stop=c.getString("stop");
String date=c.getString("date");
String time=c.getString("time");
String price=c.getString("price");
HashMap<String,String>map=new HashMap<String,String>();
map.put("companyname",companyname);
map.put("cod",cod);
map.put("bign",bign);
map.put("stop",stop);
map.put("date",date);
map.put("time",time);
map.put("price",price);
P.add(map);
}
}else {
Toast.makeText(MainActivity.this,"No DataFound",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(MainActivity.this, P, R.layout.item_list,
new String[]{"companyname", "cod", "bign", "stop", "date", "time", "price"},
new int[]{R.id.companyname, R.id.cod, R.id.bign, R.id.stop, R.id.date, R.id.time1, R.id.price});
setListAdapter(adapter);
}
});
}
}
}
my JSONParser code:
package com.example.delta.travel;
import android.net.http.HttpResponseCache;
import android.util.Log;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Date;
import java.util.List;
/**
* Created by delta on 5/28/2016.
*/
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;
}
}
and my travel.php code:
<?php
$con=mysqli_connect("localhost","root","","travels");
mysqli_set_charset($con,"utf8");
$response=array();
$result=mysqli_query($con,"select * from travel");
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$temp=array();
$temp["companyname"]=$row["companyname"];
$temp["cod"]=$row["cod"];
$temp["bign"]=$row["bign"];
$temp["stop"]=$row["stop"];
$temp["date"]=$row["date"];
$temp["time"]=$row["time"];
$temp["price"]=$row["price"];
$response["travel"]=array();
array_push($response["travel"],$temp);
}
$response["t"]=1;
echo json_encode($response);
}
else{
$response["t"]=0;
$response["message"]="Not Found";
echo json_encode($response);
}
?>
1) Change the code in your JSONParser class with this code. use only this fiction.
public JSONObject makeHTTPRequest(String urlString, String method) {
if(method.equals("POST")){
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
json = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else if(method.equals("GET")){
URL url = null;
try {
url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
json = sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
2) And in MainActivity you have to add P = new ArrayList<>(); in onCreate() method like this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
P = new ArrayList<>();
new travel().execute();
}
All done it is working at my side. it should definitely work for you too.
Do some changes and see if it works :
new travel().execute(url);
Your AsyncTask :
class travel extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("login");
pd.show();
}
#Override
protected String doInBackground(String... params) {
// List<NameValuePair> parms=new ArrayList<>();
for(urlString in params){
JSONObject json=jParser.makeHTTPRequest(urlString,"GET");
}
//rest is same
In JSONParser Class :
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){
//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();
}
// Rest is same
How to go next page? After check user, Password is right.
I write this code
startActivity(new Intent(this, getMenu.class));
on
public void OnLogin(View view)
{
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
it not check user&password. But always go to next.
I know is really stupid question. But I really don't know.
Please tell me. :'(
(sorry for my bad English.)
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText UsernameEt ,PasswordEt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText)findViewById(R.id.etUserName);
PasswordEt = (EditText)findViewById(R.id.etPassword);
}
public void OnLogin(View view)
{
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
public void OpenReg(View view){
startActivity(new Intent(this,Register.class));
}
public void getJSONClick(View view){
startActivity(new Intent(this, getDatabase.class));
}
}
Backgroundwrok.java
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by puen on 4/6/2016.
*/
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.10.125/login.php";
String register_url = "http://192.168.10.125/register.php";
if(type.equals("login")){
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while ((line = bufferedReader.readLine())!= null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else if (type.equals("register")){
try {
String name = params[1];
String surname = params[2];
String age = params[3];
String username = params[4];
String password = params[5];
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"
+URLEncoder.encode("surname","UTF-8")+"="+URLEncoder.encode(surname,"UTF-8")+"&"
+URLEncoder.encode("age","UTF-8")+"="+URLEncoder.encode(age,"UTF-8")+"&"
+URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while ((line = bufferedReader.readLine())!= null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
getData.java
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class getDatabase extends AppCompatActivity {
String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_database);
}
public void getJSON(View view)
{
new BackgroundTask().execute();
}
class BackgroundTask extends AsyncTask<Void,Void,String> {
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://192.168.10.125/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream =httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine())!=null)
{
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.tv3);
textView.setText(result);
}
}
}
Hi, i don't undestand why this doesn't work, i am trying to retrieve whatever comes after "offer" in the specified url and then display it but when i click on the Offer button on android screen nothing happens. Please help if you could. I have the internet permission in manifest.
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.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
public class LoggedIn extends Activity {
AlertDialog alertDialogStores;
ObjectItem[] ObjectItemData = new ObjectItem[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logged_in);
// a button to show the pop up with a list view
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonShowPopUp:
LoaderTask task = new LoaderTask();
task.execute();
break;
}
}
};
findViewById(R.id.buttonShowPopUp).setOnClickListener(handler);
}
class LoaderTask extends AsyncTask<Void , Void ,String>{
ProgressDialog progressDialog ;
public LoaderTask(){
progressDialog = new ProgressDialog(SplashActivity.this);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading app data...");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return connect("http://ec2-54-175-18-179.compute-1.amazonaws.com/customers/37.json");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
showPopUp(result);
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
//Log.i(TAG,response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
instream.close();
return result;
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
public void showPopUp(String result){
try{
JSONArray jsonArray = new JSONArray(result);
for(int i = 0 ; i <= 5 ; i++){
JSONObject o = jsonArray.getJSONObject(i);
String http_response = o.getString("offer");
System.out.println("test "+http_response);
//ObjectItemData[i] = new ObjectItem(o);
ObjectItemData[0] = new ObjectItem(http_response);
ObjectItemData[1] = new ObjectItem(http_response);
ObjectItemData[2] = new ObjectItem(http_response);
ObjectItemData[3] = new ObjectItem(http_response);
ObjectItemData[4] = new ObjectItem(http_response);
// adapter instance
ArrayAdapterItem adapter = new ArrayAdapterItem(this, R.layout.list_view_row_item, ObjectItemData);
// create a new ListView, set the adapter and item click listener
ListView listViewItems = new ListView(this);
listViewItems.setAdapter(adapter);
listViewItems.setOnItemClickListener(new OnItemClickListenerListViewItem());
// put the ListView in the pop up
alertDialogStores = new AlertDialog.Builder(LoggedIn.this)
.setView(listViewItems)
.setTitle("Offers")
.show();
}
} catch(Exception e){e.printStackTrace();}
finally{System.out.println("Success");
}
}
}
class LoaderTask extends AsyncTask<Void , Void ,String>{
ProgressDialog progressDialog ;
public LoaderTask(){
progressDialog = new ProgressDialog(SplashActivity.this);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading app data...");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return connect("http://ec2-54-175-18-179.compute-1.amazonaws.com/customers/37.json");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
showPopUp(result);
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
//Log.i(TAG,response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
instream.close();
return result;
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
public void showPopUp(String result){
try{
JSONArray jsonArray = new JSONArray(result);
for(int i = 0 ; i < jsonArray.length() ; i++){
JSONObject o = jsonArray.getJSONObject(i);
String http_response = o.getString("offer");
System.out.println("test "+http_response);
ObjectItemData[i] = new ObjectItem(http_response);
}
//and populate your listview here
} catch(Exception e){e.printStackTrace();}
finally{System.out.println("Success");
}
}
and call this to do task
new LoaderTask().execute();
I have a server made in python that reads the querystring-message and stores it in a sqlite database, and then displays the content.
Now I want to send the message from a android application. This is my code so far.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button send;
TextView display;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send = (Button)findViewById(R.id.button1);
display = (TextView)findViewById(R.id.editText1);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
post();
}
catch(Exception e)
{
display.setText("Det sket sig");
}
}
public void post() throws UnsupportedEncodingException
{
message = display.getText().toString();
String data = URLEncoder.encode("?message", "UTF-8")
+ "=" + URLEncoder.encode(message, "UTF-8");
String text = "";
BufferedReader reader=null;
try
{
URL url = new URL("http:homepage.net");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception e)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
display.setText(text);
}
});
}
#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;
}
}
This is not functioning as per the expectations. What am i doing wrong here?
for network related operation you have to use asynctask or thread other wise you wil get NetworkOnMainThread Exception.
refer here
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
Use following AsyncTask to make server request:
public class RestServiceTask extends AsyncTask<String, Void, String> {
private String errorMessage;
public RestServiceTask() {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String url = params[1];
String method = params[2];
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
HttpConnectionParams.setSoTimeout(httpParameters, 60000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpUriRequest request;
try {
if (method.equals("get")) {
request = new HttpGet(url);
} else {
request = new HttpPost(url);
if (params.length > 0 && params[0] != null) {
StringEntity entity = new StringEntity(params[0]);
((HttpPost) request).setEntity(entity);
Crashlytics.log(Log.INFO, "Request", params[0]);
}
((HttpPost) request).setHeader("Content-Type",
"application/json");
}
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String json = convertStreamToString(entity.getContent());
Crashlytics.log(Log.INFO, "Response", json);
return json;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//process your result
}
public String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
}
Use it by:
new RestServiceTask().execute("<json string>",url,method);//method can be get,post
try this simple example if you have any doubt follow this links:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.codeincloud.tk/First.php");
try {
HttpResponse response = httpclient.execute(httppost);
final String str = EntityUtils.toString(response.getEntity());
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(str);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://codeoncloud.blogspot.in/2012/07/android-php-web-service-client.html,http://sampleprogramz.com/android/singlewebservicecall.php
You should change the title of your question, there is no such thing as queryString in a POST. Query String parameters only gets added in a GET, and in POST you pass data in the body of the request.
Also, you could use this in combination with AsyncTask to solve your problem
EDIT: Also, Check here for more about GET and POST
Try this :
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(your website);
List<NameValuePair> entityParams = new ArrayList<NameValuePair>();
entityParams.add(new BasicNameValuePair("action", "postcomment"));
entityParams.add(new BasicNameValuePair("app_id", com.appbuilder.sdk.android.Statics.appId));
entityParams.add(new BasicNameValuePair("message", message1));
entityParams.add(new BasicNameValuePair("message2", message2));
httpPost.setEntity(new UrlEncodedFormEntity(entityParams, "utf-8"));
String resp = httpClient.execute(httpPost, new BasicResponseHandler());