I have pc running node in the same wifi with development phone(i dont use virtual device).
I test nodejs server with firefox extension rested and works fine(same pc with server)
I try to post from my android app a simple json. No error thrown but no seems to work(I have a console.log() on server's .post which not shown). I have also open 8080 port. here is my android code
public void sendJson(View view) {
new LongOperation().execute();
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://192.168.1.5:8080/api");
URLConnection urlConn;
DataInputStream input;
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("name", "kalosto");
// Send POST output.
OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream ());
printout.write(jsonParam.toString());
printout.flush ();
printout.close ();
} catch (Exception e) {
e.printStackTrace();
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
I change the request from post to get, from my phone browser i can access the server and the console.log be triggered but app still do nothing
Related
Very new at Android development. Trying to call a webservice in Android Studio and getting this: java.net.SocketTimeoutException: SSL handshake timed out. I dont see traffic with wireshark and am not sure at what point its failing. Does not seem to leave the emulator.
EDIT: The webservice contains three methods, for lack of better term. I am not sure how to call the proper method in android. In powershell I call like this:
Powershell:
$myname = New-WebServiceProxy -Uri $URI -Namespace myname-class ssl
$myname.webservicemethod($qualifications,0,30)
Android:
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button2);
final TextView textview = findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
AsyncTask asyncTask = new AsyncTask()
{
#Override
protected Object doInBackground(Object[] objects)
{
OkHttpClient client = new OkHttpClient();
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://ip of webservice/pathvalue/WSDL/public/hostname/name").newBuilder();
urlBuilder.addQueryParameter("username", "someuser");
urlBuilder.addQueryParameter("password", "somepass");
urlBuilder.addQueryParameter("qualification", "Assigned Group=Admin Group");
String url = urlBuilder.build().toString();
Request request = new Request.Builder().url(url).build();
Response response = null;
try
{
response = client.newCall(request).execute();
return response.body().string();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o)
{
textview.setText(o.toString());
}
}.execute();
}
});
}
}
I suspect preventing SocketTimeoutException is beyond our limit. One way to effectively handle it is to define a connection timeout and later handle it by using a try catch block. Hope this will helps
HttpUrlConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(7000); //set the timeout in milliseconds
The Problem
I have an AsyncTask task called from an Activity's OnCreate method. This task makes an http request. The HTTP request hangs. Once the "CODE HANGS HERE" code in the code below is executed, I observe in the debugger that the Async threads are perpetually 'running' and never return anything.
The Code
Here's the OnCreate method of the activity:
protected void onCreate(Bundle savedInstanceState) {
asyncRequest.delegate = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_attach);
Button retakeButton = (Button) (findViewById(R.id.retake_button));
retakeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(AttachActivity.this, MainActivity.class);
startActivity(intent);
}
});
try {
URL url;
url = new URL("http://btl-cromwell:9000/api/engine/v1/version");
asyncRequest.execute(url);
} catch (Exception e) {
Log.e(logtag, e.toString());
}
}
Note the URL that is passed to he async task should just return JSON containing the version number of the service receiving the request.
The async task (asyncRequest) code is below:
public class AsyncRequest extends AsyncTask<URL, Void, List<String>> {
private String logtag = "AsyncRequestTask";
public AsyncResponse delegate;
List<String> projects = new ArrayList<String>();
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected List<String> doInBackground(URL... urls) {
try {
// Creating & connection Connection with url and required Header.
HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("GET"); //POST or GET
urlConnection.setRequestProperty("User-Agent", "Test");
// CODE HANGS HERE
int responseCode = urlConnection.getResponseCode();
String responseMessage = urlConnection.getResponseMessage();
projects.add(responseMessage);
} catch (Exception e) {
Log.e(logtag, e.toString());
}
return projects;
}
#Override
protected void onPostExecute(List<String> result){
delegate.processFinish(result);
}
}
Once I have the request working I will populate the projects variable with what I actually want to return but for now I just have it set to responseMessage. I'm sure this is just something to do with my unfamiliarity in making requests in Java, but I have spent days on this and can't figure it out. Any help is greatly appreciated.
asyncRequest.execute(url);
asyncRequest.getStatus();
String[] projects = asyncRequest.get();
It is not possible to do both an .execute and a .get().
As you should never use .get(), you better remove that statement.
Remove all code after asyncRequest.execute(url); and put that code in the onPostExecute of your AsyncTask.
I'm trying to create a connection to a servlet and send a Json File, here is the part of the code where the app crashes:
findViewById(R.id.main_login_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalJson=createJfile();
try {
HTTPConnection(finalJson);
} catch (IOException e) {
e.printStackTrace();
}
}
});
The function is the following one:
public void HTTPConnection(String Json) throws IOException{
URL url;
url = new URL("http://192.168.0.136:8080/ProgettoProva/AndroidApp");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Accept", "text/json");
OutputStreamWriter writer =new OutputStreamWriter(conn.getOutputStream());
writer.write(Json);
writer.close();
conn.disconnect();
}
In the LogCat, nothing is showed. The app just crashed when it starts the function.
You should execute network code in a AsyncTask. Android does not allow Networking in the main Thread.
private class MyAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
//Do network code here
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
Execute with
new LongOperation().execute();
Im making an app that requires the HttpURLConnection. I tested it on the emulator and on my
Optimus S version 2.3.3 but when i test it on my Galaxy S3 version 4.1.2 it automatically fails. The LogCat doesn't show any errors. So im wondering why it fails on the Galaxy S3.
Http Setup
System.setProperty("http.keepAlive", "false");
URL check_url = new URL("http://www.website.com");
HttpURLConnection http = (HttpURLConnection) check_url.openConnection();
http.setConnectTimeout(3000);
http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
http.setRequestMethod("GET");
http.connect();
Some Android version (I don't known) need an AsyncTask to make HTTP connection, so you must to put your code in a background thread like that.
public void makeSingUp(){
new AsyncTask<Void, Void, Boolean>(){
#Override
protected Boolean doInBackground(Void... params){
//Your code connection
return true;
}
#Override
public void onPostExecute(Boolean result){
//Some message that indicates the connection was finished, or nothing.
}
}.execute();
}
download volley lib and add in your project. tutorial [link]: http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
public class send_data extends AsyncTask {
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(main.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setTitle("please wait...");
mProgressDialog.show();
}
protected String doInBackground(String... args) {
String url = "http://your_url";
try {
ArrayList<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>(
1);
nvp.add(new BasicNameValuePair("key for your data","yourdata"));
String str_responsebody = obj_service.executer(url, nvp);
Log.i("responce", str_responsebody + "===");
return str_responsebody;
} catch (Exception e) {
Log.i("error1", "" + e.toString());
return null;
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
Log.i("result", result);
mProgressDialog.dismiss();
}
} catch (Exception e) {
Log.e("error2", "" + e.toString());
e.printStackTrace();
mProgressDialog.dismiss();
}
}
}
I'm having a really tough nut to crack with a bug. Api being used is v11, honeycomb 3.0
I have a asynctask inside a fragment downloading from a XML api with basic authentication. It works perfectly even when i change the parameters from the fragment within with the edittexts etc. But when i try to mutate a autocompletetextview from outside the fragment, suddenly i get a "no element at line 1. column 0" exception. I tried the androidhttpclient, fiddled with systemprop(http.keepalive), and completly narrowed it down to this method.
public void setStations(String a, String b){
AutoCompleteTextView fromET = (AutoCompleteTextView ) getView().findViewById(R.id.from);
fromET.setText(a);
AutoCompleteTextView toET = (AutoCompleteTextView) getView().findViewById(R.id.to);
toET.setText(b);
}
When this method executes it botches up my downloadtask somewhere. If i manually edit these textview it works fine.
class LoadDataTask extends AsyncTask<String, Integer, ArrayList<Reisadvies>> {
private Exception ex;
private ProgressDialog pd;
protected void onPreExecute() {
//loadprogressdialog
}
protected ArrayList<Reisadvies> doInBackground(String... params) {
try{
ex = null;
return new APIreader().getRA(params[0], params[1], params[2],params[3],params[4],params[5], params[6]);
}catch (Exception e){
cancel(true);
pd.dismiss();
ex = e;
return null;
}
}
protected void onPostExecute(ArrayList<Reisadvies> ra){
//send list to activity
}
protected void onCancelled() {
super.onCancelled();
showError(ex);
}
}
};
public ArrayList<Reisadvies> getRA(String fromStation, String toStation, String viaStation, String dateTime, String departure, String hslAllowed, String yearCard) throws APIException{
try{
String uri = url(fromStation, toStation, viaStation, dateTime, departure, hslAllowed,yearCard);
URL url = new URL(uri);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
if (!url.getHost().equals(uc.getURL().getHost())) {
throw new APIException("HotspotForwadingActive");
}
String basicAuth = "Basic " + "username:password"; //base64 encoded
uc.setRequestProperty ("Authorization", basicAuth);
uc.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
try{
return (ArrayList<Reisadvies>) new XMLParser().parseRP(in);
}finally{
uc.connect();
}
}catch (Exception e){
e.printStackTrace();
throw new APIException(e.getMessage());
}
}
I think there is a problem in doInBackground:
pd.dismiss();
You can do operations on UI element only in UI Thread. It means that you can do this in onPostExecute method, or, if you want, you can use runOnUiThread method:
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
I hope this is helpful...
You are right about that too, but the problem was different. Just found out that it was to urlencoding. Should have figured that out right away but was throw off by the fact that it worked sometimes with a space in it :)