My Android app can't connect to server - java

I'm tying to read data from server I'm using xampp) but the data is empty
this is my connect activity:
public String link="";
public AsyncTaskConnect(String link){
this.link=link;
}
#Override
protected Object doInBackground(Object[] params) {
try{
URL url=new URL(link);
URLConnection connection=url.openConnection();
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder builder=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
builder.append(line);
}
MainActivity.data=builder.toString();
}catch (Exception e){
}
return "";
}
this is main activity:
public static String data="";
TextView txthello;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txthello=(TextView)findViewById(R.id.txthello);
new AsyncTaskConnect("http://192.168.1.2/digikala/test.php").execute();
txthello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,data,Toast.LENGTH_LONG).show();
}
});
}
but it doesn't work, what should I do?

but the data is empty
Because execute is not a blocking call.
Assuming you can actually reach the server, MainActivity.data is an empty String until after the Asynctask onPostExecute
You can either use Volley, Okhttp, Retrofit, etc to simplify your networking code
Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley
or add callbacks into your Asynctask
How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

Using HttpURLConnection, it extends your URLConnection so I am changing just a little to your code. Given you have your query in the String variable link, this should work just as fine.
try {
URL url = new URL(link);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
int responseCode = connection.getResponseCode();
Log.i(TAG, "POST Response Code: " + responseCode);
//Takes data only if response from WebService is OK
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
//Stores input line by line in response
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
if you follow this snippet, response is the string which contains all of the response you get from your webservice, you can further convert it to JSON if you want.
Hope it works!

Related

How to get the response until the server complete?

Here is the Server class within the server connection. I need to get the response and check the result after the server process complete. The following codes only check the result before got the respond.
public class Server {
String line;
StringBuilder stringBuilder = new StringBuilder();
public void httpPost(String URL) {
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
stringBuilder.setLength(0);
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
button.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
server.httpPost("https://google.com?username=Peter");
if (server.stringBuilder.toString().contains("Successful")){
Log.d("test",server.stringBuilder.toString());
}
}
}
});
Why you don't use retrofit library? Retrofit easy way to work with api's.
You can find here retrofit library
Retrofit has two callback:
call.enqueue(callback) - asynchronous, runs the request on a background thread, and runs the callback on the current thread
call.execute() - synchronous, runs the request on the current thread.
I use call.enqueue(callback). Because this is asynchronous and this callback does not freeze ui components.
You need learn REST API libraries volley, retrofit or ktor.
You can use any library.
Volley: https://google.github.io/volley/
Retrofit: https://square.github.io/retrofit/
Ktor: https://ktor.io/

Async Task to Save data in SQL server in Android

I am trying to save edit box data in SQL server by using android app. I am trying to use async task to save data.I already developed web service and host in the IIS which is running fine. So i Need now code in android to save data.
This is my Aysnc Task
class SaveScan extends AsyncTask<String,Void, String>{
String status = null;
protected void onPreExecute(){
}
protected String doInBackground(String... connUrl){
HttpURLConnection conn = null;
BufferedReader reader;
try{
final URL url = new URL(connUrl[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setChunkedStreamingMode(0);
conn.addRequestProperty("Content-Type","application/json: charset=utf-8");
conn.setRequestMethod("POST");;
JSONObject jsonObject = new JSONObject();
jsonObject.put("scans",Scan1);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
out.write(jsonObject.toString().getBytes());
out.close();
int result = conn.getResponseCode();
if (result == 200) {
InputStream in = new BufferedInputStream(conn.getInputStream());
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while((line =reader.readLine()) != null){
status = line;
}
}
}catch(Exception ex){
}
return status;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
if(result != null){
Toast.makeText(MainActivity.this,"Scan Saved ",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Not Saved",Toast.LENGTH_LONG).show();
}
}
}
This is Mine Button Call
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{
Manifest.permission.CAMERA},
100);
Intent intent = new Intent(MainActivity.this, Scan.class);
startActivity(intent);
}
});
private void onSaveClicked() {
new SaveScan(url).execute();
}
private class SaveScan extends AsyncTask<String,Void, String>{
String status = null;
protected String doInBackground(String... connUrl){
try {
// This is getting the url from the string we passed in
URL url = new URL(connUrl[0]);
// Create the urlConnection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
// OPTIONAL - Sets an authorization header
urlConnection.setRequestProperty("Authorization", "someAuthString");
JSONObject jsonObject = new JSONObject();
jsonObject.put("scans","someString");
// Send the post body
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(jsonObject.toString());
writer.flush();
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = convertInputStreamToString(inputStream);
status=response ;
// From here you can convert the string to JSON with whatever JSON parser you like to use
} else {
// Status code is not 200
// Do something to handle the error
status=null;
}
} catch (Exception e) {
Log.d("SaveScan", e.getMessage());
}
return status;
}
private String convertInputStreamToString(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
try {
while((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
protected void onPostExecute(String result){
super.onPostExecute(result);
if(result != null){
Toast.makeText(MainActivity.this,"Scan Saved ",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,"Not Saved",Toast.LENGTH_LONG).show();
}
}
}
You can choose between different storage frameworks such as Room, SQLite or Preferences depending on your data. Room and SQLite are relational databases, where SQLite requires developers to create tables and map relationships, Room takes care of those with the help of annotation processing. Preferences are android's storage framework where you can store minimal amount of data for example settings for your app, map app's flow and vital data such as user information. In the end, it all depends on the time you can spend and the data that you are trying to save. I suggest you go through all these frameworks and identify what's best for you.

AsyncTask to display Response form WCF

I wrote a Restful WCF service and it is deployed on IIS. I have been attempting to consume the WCF Service using a AsyncTask Thread. I built the thread in to the main UI class so that I can update the GUI.
public class ServiceRunning extends AsyncTask<String, Void, String>{
private Exception exception;
String line = "";
public void setLine(String line)
{
this.line = line;
}
public String getLine()
{
return line;
}
#Override
protected String doInBackground(String... url) {
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri = new URI(url[0]);
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json; charset=utf-8");
HttpResponse response = httpClient.execute(httpget);
HttpEntity responseEntity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// while ((line = rd.readLine()) != null) {
// Log.d("****Status Line***", "Webservice: " + line);
// }
while((line = rd.readLine()) != null)
{
setLine(line);
Log.d("****Status Line***", "Webservices: " + getLine());
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "String :" + line;
}
protected void onPostExecute(String result) {
TextView txt = (TextView)findViewById(R.id.textView1);
txt.setText(getLine());
}
}
In the code, I write the response to a String and I attempt to display it after execution. For some resound, when I run the program I don't get the response, I get a blank TextView but the message displays in the Eclipse LogCat. I cant find the problem, what causes this?
AsyncTask is tied to the activity kicking it off. If you rotate the device or the app goes into the background, is added or removed from a dock, the original activity is destroyed. The AsyncTask continues though and responds to the original activity that is no longer visible.
You are better off using an IntentService or Service to call web services, it is a much more reliable pattern.

Post JSON in android

I want to post String data over HttpClient in android
but i'm tired after receive response status code 503 - service unavailable and
return response as Html code for our url.
I write in the following Code in JAVA Application and i return the data but when I write the same code in Android Application i receive an exception file I/O not found, I'm Puzzled for this case:
public void goButton(View v)
{
try{
URL url = new URL("https://xxxxxxxxx");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Test ts= new ApiRequest("null","getUserbyID",new String[] { "66868706" });
String payLoad = ts.toString(); //toSting is override method that create //JSON Object
System.out.println("--->>> " + payLoad);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
System.out.println("=================>>> "+ payLoad);
wr.write(payLoad);
wr.flush();
BufferedReader rd = new BufferedReader(new nputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println("-->> " + line);
response += line;
}
wr.close();
rd.close();
System.out.println("=================>>> "+ response);
} catch (Exception e) {
e.printStackTrace();
System.out.println("=================>>> " + e.toString());
throw new RuntimeException(e);
}
I try to put this code in AsynTask, Thread but i receive the same response status code.
I write in the following Android code as an example data
public void goButton(View v)
{
try{
new Thread(new Runnable() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000); // Timeout Limit
HttpResponse response;
String url = "https://xxxxxxxxxxxxx";
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
json.put("service","null");
json.put("method", getUserByID.toString());
json.put("parameters", "1111");
System.out.println(">>>>>>>>>>>" + json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
String response = client.execute(post);
if (response != null) {
String temp = EntityUtils.toString(response.getEntity());
System.out.println(">>>>>>>>>>>" + temp);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(">>>>>>>>>>>" + e.getMessage());
}
}
}).start();
}
Please Help me to find solution for this problem :(
Thank you in advance
Here is an code snippet , hoping it will help you.
1)An function which carries the http get service
private String SendDataFromAndroidDevice() {
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet getMethod = new HttpGet("your url + data appended");
BufferedReader in = null;
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient
.execute(getMethod);
in = new BufferedReader(new InputStreamReader(httpResponse
.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2) An Class which extends AsyncTask
private class HTTPdemo extends
AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
String result = SendDataFromAndroidDevice();
return result;
}
#Override
protected void onProgressUpdate(Void... values) {}
#Override
protected void onPostExecute(String result) {
if (result != null && !result.equals("")) {
try {
JSONObject resObject = new JSONObject(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3) Inside your onCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView("your layout");
if ("check here where network/internet is avaliable") {
new HTTPdemo().execute("");
}
}
This code snippet ,
Android device will send the data via URL towards Server
now server needs to fetch that data from the URL
Hey Mohammed Saleem
The code snippet provided by me works in the following way,
1)Android device send the URL+data to server
2)Server [say ASP.NET platform used] receive the data and gives an acknowledgement
Now the Code which should be written at client side (Android) is provided to you, the later part of receiving that data at server is
Server needs to receive the data
An webservice should be used to do that
Implement an webservice at server side
The webservice will be invoked whenever android will push the URL+data
Once you have the data ,manipulated it as you want

Why do I keep getting java.net.ConnectException in my Android application?

I have recently refactored some of my networking code in my android app to use the Google recommended HTTPUrlConnection. Previously, I was using Apache's HTTPClient. I'm not sure if either of those things are relevant.
The other thing I have recently done to my networking code is use AsyncTask for the calls. Previously I was just doing work on the main thread (obviously bad) and so my application would appear to hang when fetching data. The thing is, since switching to AsyncTask, I have pretty regularly experienced timeout errors.
Why do I get this timeout error?
java.net.ConnectException: failed to connect to <url> (port 80): connect failed: ETIMEDOUT (connection timed out)
Here is my AsyncTask that makes the network call.
private class PostToPHP extends AsyncTask<PostToPHP, Void, String>
{
private String functionName;
private ArrayList<NameValuePair> postKeyValuePairs;
public PostToPHP(String function, ArrayList<NameValuePair> keyValuePairs)
{
functionName= function;
postKeyValuePairs = keyValuePairs;
}
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(BaseActivity.getInstance(), "Loading", "Please wait...", true, false);
}
#Override
protected String doInBackground(PostToPHP... params)
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(FUNCTION_NAME, functionName));
for (int i = 0; i < postKeyValuePairs.size(); i++) {
nameValuePairs.add(postKeyValuePairs.get(i));
}
try {
URL url = new URL("www.myurl");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept-Charset", iso-8859-1);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, iso-8859-1));
writer.write(getEncodedPostParameters(nameValuePairs, iso-8859-1));
writer.close();
os.close();
InputStream is = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, iso-8859-1));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
urlConnection.disconnect();
return sb.toString();
}
catch (UnknownHostException e) {
// handle it
return null;
}
catch (Exception e) {
// this is where I'm always getting a timeout exception
return null;
}
}
#Override
protected void onPostExecute(String result)
{
progressDialog.dismiss();
}
}
EDIT: I thought this only occurred during one particular network call but I've now experienced it at various places.
EDIT 2: Looking at this again I found this and I think that's more of my problem. This didn't exist before I implemented Android AsyncTask for the network calls. I think that AsyncTask is somehow screwing up with threading and causing the timeouts.
You could explicitly set the timeout for the HTTPUrlConnection:
urlConnection.setConnectionTimeout(aLongerTimeout)
I'm not very satisfied with this answer, but it seems to be working. I think there must be an issue with my code, or a bug in HTTPUrlConnection of some sort. I know Google said it had bugs in Froyo and lower, but I'm seeing oddities in 2.3.4 and 4.2 which I'm testing with. Essentially I replaced my code above with Apache's code and I'm not seeing the timeouts.
private static String post(ArrayList<NameValuePair> params){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpreq = new HttpPost("www.url.com");
httpreq.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httpreq);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, NetworkConstants.HTTP_ACCEPTED_CHARSET), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
return sb.toString();
}

Categories

Resources