my httpresponse can connect to xamp.. it have failed to conncet server !! output with this code
please help me to get solution..
package com.zul.app.login;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.h
ttp.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private EditText txtUser;
private EditText txPass;
private EditText txStatus;
private Button btnLogin;
private String url ="http://192.168.42.175/loginandroid/cekuser.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtUser = (EditText) findViewById(R.id.user);
txPass = (EditText) findViewById(R.id.pass);
txStatus = (EditText) findViewById(R.id.statuslog);
btnLogin =(Button) findViewById(R.id.btlogin);
btnLogin.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
url = "http://192.168.42.175/loginandroid/cekuser.php";
url +="?user="+txtUser.getText().toString()+"&pass="+txPass.getText().toString();
getRequest(txStatus,url);
};
});
};
this is my http respon:
public void getRequest(EditText txtResult, String Surl){
Log.d("getRequest",Surl);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Surl);
try{
HttpResponse response = client.execute(request);
txtResult.setText(request(response));
}catch (Exception e){
txtResult.setText("Failed Conect To Server!!");
};
};
private String request(HttpResponse response) {
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line+"\n");
}
in.close();
result = str.toString();
}catch (Exception e){
result="error";
};
return result;
}
};
ihave permission with
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
if i run this project i dont have error but can't connect to server or failed to acces my localhost
i have php file with this link loginandroid/cekuser.php
if i use browser in android i can connect to xamp but if i use my project i cant connect
result:
failed to connect server
logcat :
08-11 10:50:36.231 19556-19556/com.zul.app.login D/getRequest: http://192.168.42.175/loginandroid/cekuser.php?user=&pass=
08-11 10:50:36.256 19556-19556/com.zul.app.login I/System.out: main calls detatch()
Related
I'm trying to connect to a servlet in localhost from my Android Emulator.
I created a project in Eclipse named SimpleHttpGetRequest with an activity named "HttpGetServletActivity".
I created in NetBeans a project named "HttpGetRequest" containing a servlet.
The code in my "HttpGetServletActivity" activity is :
package com.mobdev.simplehttprequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
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.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static final String URL = "http://10.0.2.2:8080/HttpGetRequest/HelloWorldServlet";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[]{ URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("get");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
The source code of my servlet is :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
public HelloWorldServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
}
I deployed my servlet in Apache server (i'm using xampp);
I added permission for network connection
When I run my App and click on the button, the App crashes, and I don't know why !!
Can anybody help me, please ? Im' stuck.
I tried :
Wifi connection : I did run my App on a real device, instead of "10.0.2.2" I put the ip adress of my PC but it doesn't work ;
Access to project HttpGetrequest from Android Emulator browser, it worked ;
This question already has answers here:
What is the way to run a new thread and a UI thread in Android? [closed]
(3 answers)
Closed 8 years ago.
I'm trying to write a code which signups a user. The php script is running fine. But code is android code is not working. Values not going on server.
package com.androidexample.httpgetexample;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class HttpGetAndroidExample extends Activity {
TextView content;
EditText fname,email,login,pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_get_android_example);
content = (TextView)findViewById(R.id.content);
fname = (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
login = (EditText)findViewById(R.id.loginname);
pass = (EditText)findViewById(R.id.password);
Button saveme=(Button)findViewById(R.id.save);
saveme.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
//ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Please wait, connecting to server.",
Toast.LENGTH_LONG).show();
try{
String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
String fnameValue = URLEncoder.encode(fname.getText().toString(), "UTF-8");
String emailValue = URLEncoder.encode(email.getText().toString(), "UTF-8");
String passValue = URLEncoder.encode(pass.getText().toString(), "UTF-8");
HttpClient Client = new DefaultHttpClient();
String URL = "http://nishtha.comze.com/log.php?user="+loginValue+"&name="+fnameValue+
"&email="+emailValue+"&pass="+passValue;
//Log.d("httpget", URL);
try
{
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpResponse response = Client.execute(httpget);
Log.d("Http Response:", response.toString());
String SetServerString = "";
SetServerString = Client.execute(httpget, responseHandler);
content.setText(SetServerString);
}
catch(Exception ex)
{
content.setText("Fail!");
}
}
catch(UnsupportedEncodingException ex)
{
content.setText("Fail22");
}
}
});
}
}
When I run the code it olways display "Fail"
You need to use AsyncTask<> or IntentService to handle your request.
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 am trying to get an image from my data base and insert it using imageView in android
my php code:
<?php
if(isset($_POST["IdToSearch"]) && $_POST["IdToSearch"] != "") {
$firstid = $_POST["IdToSearch"];
$con = mysqli_connect("localhost","root","","bdUniv");
if(mysqli_connect_errno()) {
echo'Database connection error: '. mysqli_connect_error();
exit();
}
$firstid = mysqli_real_escape_string($con,$firstid);
$userdetails = mysqli_query($con,"SELECT * FROM Etudiant WHERE id = '$firstid'");
if(!$userdetails) {
echo'Couldnotrunquery: '. mysqli_error($con);
exit();
}
$row = mysqli_fetch_row($userdetails);
$result_data = array(
'id' => $row[0],
'nom' => $row[1],
'prenom' => $row[2],
'age' => $row[3],
'photo' => $row[4],
);
echo json_encode($result_data);
}else{
echo"Could not complete query. Missingparameter";
}
?>
My java code:
package com.example.getdatafrombdd;
import java.io.File;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity_GET extends Activity {
Button buttonGetData = null;
EditText editTextSearchString = null;
TextView textViewId = null;
TextView textViewNom = null;
TextView textViewPrenom = null;
TextView textViewAge = null;
ImageView imgViewPhoto = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_get);
buttonGetData = (Button) findViewById(R.id.buttonGetData);
editTextSearchString = (EditText) findViewById(R.id.editTextSearchString);
textViewId = (TextView) findViewById(R.id.txtId);
textViewNom = (TextView) findViewById(R.id.txtNom);
textViewPrenom = (TextView) findViewById(R.id.txtPrenom);
textViewAge = (TextView) findViewById(R.id.txtAge);
imgViewPhoto = (ImageView) findViewById(R.id.imgPhoto);
//Setup the Button's OnClickListener
buttonGetData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Get the data
DoPOST mDoPOST = new DoPOST(MainActivity_GET.this, editTextSearchString.getText().toString());
mDoPOST.execute("");
buttonGetData.setEnabled(false);
}
});
}
#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_activity__get, menu);
return true;
}
public class DoPOST extends AsyncTask<String, Void, Boolean> {
// String: le type des paramètres fournis à la tâche.
// Void: le type de données transmises durant la progression du traitement.
// Boolean: le type du résultat de la tâche.
Context mContext = null;
String IdToSearch = "";
//Result data
int intId;
String strNom;
String strPrenom;
int intAge;
String strPictPath;
Exception exception = null;
DoPOST(Context context, String nameToSearch) {
mContext = context;
IdToSearch = nameToSearch;
}
#Override
protected Boolean doInBackground(String... arg0) {
try{
//Setup the parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// key value
nameValuePairs.add(new BasicNameValuePair("IdToSearch", IdToSearch));
//Add more parameters as necessary
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://10.0.2.2/univ/getFromUniv.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
intId = jsonObject.getInt("id");
strNom = jsonObject.getString("nom");
strPrenom = jsonObject.getString("prenom");
intAge = jsonObject.getInt("age");
strPictPath = jsonObject.getString("photo");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
textViewId.setText("Id: " + intId);
textViewNom.setText("Nom: " + strNom);
textViewPrenom.setText("Prenom: " + strPrenom);
textViewAge.setText("Age: " + intAge);
File imgFile = new File(strPictPath);
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imgViewPhoto.setImageBitmap(myBitmap);
buttonGetData.setEnabled(true);
if(exception != null){
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
When i compiled it i get the: id, name, 2nd name, age but no image found!
And the error is:
1-06 20:19:17.527: E/BitmapFactory(786): Unable to decode stream: java.io.FileNotFoundException: /home/user/images/myPict.jpg: open failed: ENOENT (No such file or directory)
Help please!
You are doing this very wrong. Your server is returning the path of the photo on the server, not in the app. When you go to open the file, your app gives you an error because the file is not found locally, which is where your app is looking. To fix this, you should either download the photo from the server in your AsyncTask or store the Internet path of your picture and use a library like Picasso to download the image at that path to the ImageView.
EDIT:
As #Zerkz noted in his comment, you could also pass the image contents itself in your JSON by encoding them in base64 and then decoding those contents to a Bitmap in your AsyncTask. This would be advantageous if you don't plan on publicly exposing the URL to any of your images or if they will eventually be stored in a database.
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.