this code works fine on emulator, but on real device it gives
java.net.SocketException:the operation timed out
ive got a php script running on my xampp server.
package com.example.new1;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tx;
StringBuilder stringBuilder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tx= (TextView)findViewById(R.id.text);
}
public void func(View view)
{
//tx.setText("Working fine till here.");
new FetchSQL().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class FetchSQL extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... arg0) {
URL url = null;
BufferedReader reader = null;
String myUrl = "http://10.22.35.4:80/conc2.php";
try
{ url =new URL(myUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15*10000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
// TODO Auto-generated method stub
return stringBuilder.toString();
}
catch(final Exception e)
{
return e.toString();
}
}
protected void onPostExecute(final String result)
{
tx.setText(result);
}
}
}
when i click on button it takes the amt of time ive set in my code, and then fails giving me the error in my textview. please help
my php code.
<?php
// attempt a connection
$dbh = pg_connect("host=10.22.35.11 dbname=iwmp_dev2 user=postgres ");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
//$sql = $_POST['pLat'];
$sql = "SELECT officer_name FROM iwmp_officer";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$array = array();
// iterate over result set
// print each row
while ($row = pg_fetch_assoc($result, null)) {
$i++;
$array = implode('+',$row);
echo $array;
}
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
java.net.SocketException exception comes when the port that you are trying to reach is not closed or not available. It takes the amount of time you have specified for searching the port and then gets out.
Firstly, try to call this service on your mobile web browser to check whether it is available or not. If it does not show that means your device is not connected to the network on which this file resides.
It may be possible that your firewall is not allowing to ping your port. When you are doing with your emulator it works since its on same PC but in case of your real device it connects via local network and some time Firewall does not allow. Solution: unblock this request on firewall or try this by closing your firewall.
Related
I have an application with 3 or more AsycTask that are called sequentially. Because these asyntasks are all similar, I created a separated class and it works properly.
Now I would like to add a progress bar in order to show something when these asynctasks ask and process the result...but not work.
My application work as follow:
I open my camera and with ZXing library I decode a qrCode
using HttpRequest I ask to my server some informations and my application processes these informations
The point is that during the processing my application shows a black screen with the tipical viewfinder of ZXing library (I think that you understand what I mean). How can replace this view with another block with a progress bar?
I already tried to modified the progress bar visibility, on the event onPreExecute and onPostExecute, also I tried to use the event onProgressUpdate, but nothig is change. The viewfinder remains on the screen until the asyncTask is not finish.
Follow my code for execute the AsyncTask:
response = asynkTaskDeleteMissionQueue.execute().get();
and my AsyncTask class
package com.klainrobotics.lucalombardi.krmir;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;
import java.util.Vector;
/**
* Created by Luca Lombardi on 27/11/2017.
*/
public class MiRCall extends AsyncTask <String, Void, List<Object> >{
public AsyncResponse delegate = null;
private String url;
private String method;
private ProgressBar progress;
public MiRCall(Context v, ProgressBar prg, String...params){
method = params[0];
url = params[1];
progress = prg;
}
#Override
protected void onPreExecute(){
}
#Override
protected void onProgressUpdate(Void... v) {
super.onProgressUpdate(v);
}
#Override
protected List<Object> doInBackground(String... arg0) {
int result = -1;
publishProgress();
List<Object> response = new Vector<Object>();
String jsonResponse = "";
BufferedReader br;
try {
URL urlMissionQueue = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlMissionQueue.openConnection();
if (connection != null) {
connection.setRequestMethod(method);
connection.setRequestProperty(Costanti.headers, Costanti.StringaHeader());
connection.setRequestProperty(Costanti.contentType, Costanti.contentTypeJSon);
customBody(connection);
connection.connect();
result = connection.getResponseCode();
response.add(result);
if (200 <= result && result <= 299) {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
for (String line; (line = br.readLine()) != null; jsonResponse += line);
response.add(jsonResponse);
}else {
Log.e("Url", "Connection is null");
}
} catch (Exception ex) {
Log.e("MiRCall", "doInBackgound: " + ex.toString());
}
return response;
}
#Override
protected void onPostExecute(List<Object> result) {
if (delegate != null) {
delegate.processFinish(result);
} else {
Log.e("MiRCall", "You have not assigned AsyncTask delegate");
}
}
public void customBody(HttpURLConnection connection) throws ProtocolException {
// Do nothing
}
}
Thanks in advance
response = asynkTaskDeleteMissionQueue.execute().get();
Pretty bad to use the .get() function on it. Do away with get(). Only start the task.
asynkTaskDeleteMissionQueue.execute();
Then in onPostExecute() handle the response.
Thanks for your suggestion. I execute
response = asynkTaskDeleteMissionQueue.execute().get();
because my asyncTask returns a list of object, so I don't know another way....
And about the original question? Any suggestions?
Thanks in any case for your time
I am trying to invoke the POST API of personality insights from Android on a button click and display the response on the screen after proper parsing. The API details of the personality insights are here.
When I tried to test this using POSTMAN I am getting the correct response. But when I try to invoke this from Android, the logcat is not showing any error and the application doesn't terminate in the emulator. The initial invocation of API is not working for me.
I referred this link for the android code
This is the code which I used. Please let me know of any mistakes that I have made.
Edited :
I also tried this example link but everything seems to be deprecated for my current android API versions.
HTTP Example.java
package com.example.httpexample;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView, button;
TextView textView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
button = (TextView)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener(){
// When user clicks button, calls AsyncTask.
// Before attempting to fetch the URL, makes sure that there is a network connection.
#Override
public void onClick(View v) {
String stringUrl = "https://gateway.watsonplatform.net/personality-insights/api/v2/profile" (https://gateway.watsonplatform.net/personality-insights/api/v2/profile%27);
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}
}
});
}
public TextView getTextView()
{
TextView txtView = (TextView)findViewById(R.id.textView2);
return txtView;
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DownloadWebpageTask.java
package com.example.httpexample;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
class DownloadWebpageTask extends AsyncTask<String, Void, String> {
private static final String DEBUG_TAG = "HttpExample";
#Override
protected String doInBackground(String... urls) {
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String downloadUrl(String myurl) throws IOException, JSONException{
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setRequestMethod("GET");
final String basicAuth = "Basic " + Base64.encodeToString(""username":password".getBytes(), Base64.NO_WRAP);
conn.setRequestProperty ("Authorization", basicAuth);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
System.out.println("first connection");
JSONObject contentItems = new JSONObject();
contentItems.put("id", "");
contentItems.put("userid", "");
contentItems.put("created", "int");
contentItems.put("updated", "int");
contentItems.put("contenttype", "");
contentItems.put("charset", "");
contentItems.put("language", "int");
contentItems.put("content", "Hi. This is the sample input");
contentItems.put("parentid", "");
contentItems.put("reply", false);
contentItems.put("forward", false);
System.out.println("connection done");
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
System.out.println("Content " + contentAsString);
MainActivity obj = new MainActivity() ;
TextView tv = obj.getTextView();
tv.setText(contentAsString + response);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
It does not seem you are sending your contentItems object anywhere - you populate it, but never include it as payload in the request.
In addition, this contentItems is just one item object you need to include in the JSON input. The JSON input should look like:
{ "contentItems": [ <item1>, <item2> ] }
and you are just creating something that fits as one of the items above.
If you are passing some simple input to the API, I would suggest you include the header Content-Type: text/plain and forget about JSON formatting for the moment, as it is going to be simpler.
I am trying to access data from localhost MYSql database.i am using XAMP for PHP. First i created a index.php file.which is saved in C:\xampp\htdocs\sample\index.php.my android code is saved in C:\Documents and Settings\SUHAIL\workspace\PHPMYSQL.while i running android on emulator data from the database is not accessed.(there is no compiation error) .My complete code is given below.
index.php(DB name:temp
Table Name: table1)
enter code here
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$con=mysqli_connect("localhost","root","","temp");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT roll FROM table1 where username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
</body>
</html>
---------------------------------------------------------------------
SignActyivity.java
---------------------------------------------------------------------
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
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 android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
public Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://10.0.2.2/sample/login.php?username="
+username+"&password="+password;
//public URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://10.0.2.2/sample/index.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful jjjj");
this.roleField.setText(result);
}
}
-------------------------------------------------------------------------------------------
MainActivity.java
--------------------------------------------------------------------------------------------
package com.example.phpmysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role,method;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}
#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;
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
}
I can't think of any good reason to do what you are doing, but your issue is as follows -
Localhost refers to the local device, on your pc, it is your pc... and on android... it is your android device.
Even if you are running on an emulator, that emulator is set to act like a real device, it does not know about the rest of your computer. What you will need to do is set up a proper web service and access your database that way, or use an sqlite db on the device properly
Also one more note, I can see youre a noob, but it's best to post only the parts of your code that you think are causing an issue, plus any errors they log. Only add other parts if people ask you to - nobody wants to spend ages trying to figure out your mess of code, especially if it looks like you havent even tried to fix/narrow down the issue yourself
I want to read all cookies from the server but I get the following error:
java.lang.IllegalStateException: Connection already established
How can I read the cookies before connecting? I tried putting the cookie read code before defining the connection but It does not work until I define the connection which establishes the connection which prevents me from reading cookies...
Any help please?
Here's my code:
package com.example.read;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
List<String> cookies = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(l);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
View.OnClickListener l = new View.OnClickListener() {
public void onClick(View v) {
EditText edt = (EditText)findViewById(R.id.editText1);
if(!edt.getText().toString().equals("")){
readData(edt.getText().toString());
}
}
};
void readData(String text){
URL url;
HttpURLConnection conn;
DataOutputStream out;
DataInputStream in;
try{
url = new URL("http://"+text);
conn = (HttpURLConnection)url.openConnection();
if(cookies==null){
conn.getHeaderField("Set-Cookie");
}
if(cookies!=null){
for(String cookie : cookies){
conn.setRequestProperty("Cookie", cookie);
}
}
conn.setDoOutput(true);
String post = "mobile_app="+URLEncoder.encode("1","UTF-8");
out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(post);
out.flush();
out.close();
in = new DataInputStream(conn.getInputStream());
String line = "";
String data = "";
while((line=in.readLine())!=null){
data+=line;
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(data);
} catch(Exception e){
System.out.println(e);
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(e.toString());
}
}
}
Your question sounds a bit strange. As a client you set the cookies before establishing the connection - if you know them. The Set-Cookie header, the server returns, can only be read as soon as the answer of the server has been returned. Then of course it's to late to set any client-cookies :-)
In other words: You simply cannot read cookies from the server before you send the request.
The server sends "Set-Cookie" headers, and afterwards clients send these cookies with every following request. So you can set your "Cookie" headers only from the second request onwards.
package com.yarin.android.Examples_08_01;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
//以Get方式上传参数
public class Activity03 extends Activity {
private final String DEBUG_TAG = "Activity03";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
TextView mTextView = (TextView) this.findViewById(R.id.TextView_HTTP);
// http address "?par=abcdefg" is the argument to be posted
String httpUrl = "http://192.168.0.100:8080/httpGet.jsp?par=test";
// 获得的数据
String resultData = "";
URL url = null;
try {
// 构造一个URL对象
url = new URL(httpUrl);
} catch (MalformedURLException e) {
Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null) {
try {
// 使用HttpURLConnection打开连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 得到读取的内容(流)
InputStreamReader in = new InputStreamReader(
urlConn.getInputStream());
// 为输出创建BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
// 使用循环来读取获得的数据
while (((inputLine = buffer.readLine()) != null)) {
// 我们在每一行后面加上一个"\n"来换行
resultData += inputLine + "\n";
}
// 关闭InputStreamReader
in.close();
// 关闭http连接
urlConn.disconnect();
// 设置显示取得的内容
if (resultData != null) {
mTextView.setText(resultData);
} else {
mTextView.setText("读取的内容为NULL");
}
} catch (IOException e) {
Log.e(DEBUG_TAG, "IOException");
}
} else {
Log.e(DEBUG_TAG, "Url NULL");
}
Button button_Back = (Button) findViewById(R.id.Button_Back);
/* 监听button的事件信息 */
button_Back.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
/* 新建一个Intent对象 */
Intent intent = new Intent();
/* 指定intent要启动的类 */
intent.setClass(Activity03.this, Activity01.class);
/* 启动一个新的Activity */
startActivity(intent);
/* 关闭当前的Activity */
Activity03.this.finish();
}
});
}
}
For the above code, I understand how it works. It runs as an application and needs to communicate with a web server.
But I don't know how to make a web server which could be a container of "http://192.168.0.100:8080/httpGet.jsp".
I did some investigation.
(1) On Android phone, i-jetty, kws, atieews may help, but I failed to make them work for my purpose.
(2) On PC, tomcat is a good candidate to be as jsp container. But it provides localhost:8080 address, that means only application runs on PC could communicate with it. Am I right? How to make my Android phone to connect tomcat (runs on my PC)?
(3) Any other idea?
Thanks!
To make a server which can communicate with your android app you can use SOAP services or JSON. Those two are the most used ones (JSON is faster and in my opinion better to use but this can be discussed).
Take a look on some tutorials on how to create the server side app for your android app.
This is not an easy taski if you newer set up a server.