Impossible to connect to a website using HttpClient - android

I have a PHP webpage that insert a line in MySQL. What i want to do, is just to connect my android app on this page (no response from the server).
I try to connect from a service and i've heard I should use a thread to connect but it still doesn't work...
Here is my code :
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
try {
HttpUriRequest request = new HttpGet("http://localhost:8888/everbattery/post_sql.php");
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(request);
}
catch (ClientProtocolException E){}
catch (IOException E) {}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
Any ideas ? I've spend most of my afternoon on that and i'm going crazy ...

You can't go for localhost in your app.
Try putting actual IP of the machine the server is running on.
You can get to know it by using ipconfig / ifconfig.

Related

Sending message from Android client to Java server

I am developing an Android application, and I need to send a message from the application to the Java Server.
Java Server works like this:
thread = new Thread(){
public void run(){
System.out.println("Server is running...");
try {
ServerSocket socket = new ServerSocket(7000);
while(true){
Socket s = socket.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Received from client: " + dis.readUTF());
dis.close();
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
In my application I send the message in this way:
mt = new Thread() {
public void run() {
try {
Socket socket = new Socket("192.168.1.100", 7000);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(song_field.getText().toString());
dos.flush();
dos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
mt.start();
Toast.makeText(context, "Your Message is sent. Thank you!", Toast.LENGTH_SHORT).show();
I can send the message with emulator and my phone successfully, since they are connected to the same wifi connection, but if the device is not connected to the same network, message is not sent to the server. I want everybody to be able to send message to my computer server regardless of their internet connection.
How can I fix this problem?
In general you'll need to use something like Web Sockets to achieve what you're trying to do where, as would typically be the case, client/server are on different networks. There are a few different Web Socket implementations e.g. https://medium.com/square-corner-blog/web-sockets-now-shipping-in-okhttp-3-5-463a9eec82d1#.w9hrc1icw
EDIT
I initially misread question and thought you were trying to asynchronously send message from server to client (which would require something like Web Sockets). If you are just making requests from client to server then a typical solution would be to expose REST API from your server (and using something like Retrofit to make requests from client).

Connecting Android Phone to local host

In my application i am using API's which are hosted on local server, and can be accessed on network. On emulator it works fine as it is connected to proper network. When I am using app on my phone it wont.
Is it possible to access local API's through phone with our normal internet connection?
I am using below http code for accessing API's.
public String getResponse(String url, int method, String postParameter) {
HttpResponse response = null;
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(url);
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("jObj", postParameter));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
} catch (Exception e2) {
e2.printStackTrace();
}
return response.toString();
}
Is there any setting which we can do for accessing through our normal internet?
Thanks in Advance
If you have it hosted on your local machine, you will have to find a way to connect both your phone and your local machine on the same network (most commonly Wifi). A simple work-around to this is creating a hotspot in your android device and connecting your local machine to it. Make sure to set the correct IP address in the android app.
Find your local machine ip address where the api's are hosted
using ipconfig and pass on the ip address in url
your url should be like 192.168.0.102 which is assigned by modem.
Answering as I cant comment, Please check that your phone is connected to your network and not using mobile data or some other WIFI network outside of your network.

Live mjpeg video stream from server to android

I am trying to fetch mjpeg live video stream from server to android.I read this answer.it is very helpful to me.It works with this demo url.But, In my video stream it asking for username and password.
To set url into MjpegView:
setContentView(mv);
mv.setSource(MjpegInputStream.read(URL));
MjpegInputStream:
public static MjpegInputStream read(String url) {
HttpResponse res;
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
res = httpclient.execute(new HttpGet(URI.create(url)));
return new MjpegInputStream(res.getEntity().getContent());
} catch (ClientProtocolException e) {
} catch (IOException e) {}
return null;
}
As in web browser whenever i open my server link..it asking for 'password' & 'username'.so
where to put params in this read() ? and also want to know if my live video is in H.264
format. then how can i convert it into MJPEG format?Also its speed is very slow and not smooth.how to improve it?
Thanks in Advance!!
You are promted for a login because the webcam is password protected. Normally with webcams you have to pass the username and password as part of the URL. eg. username:password#ip.address.or.dyndns.com:8085/folder/stream.jpg?size=large where the number at the end is the port number.
it's been a time... but to login:
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httpget2 = new HttpGet(url);
httpget2.addHeader("Authorization","Basic " + Base64.encodeToString((USERSTRING:PASSWORDSTRING).getBytes(),Base64.DEFAULT));
res = httpclient.execute(httpget2);
return new MjpegInputStream(res.getEntity().getContent());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

why java.net.UnknownHostException: Host is unresolved: webservername.com:80?

I m implementing android app in that I m working on web api. Sometimes my app gets connected to webserver but sometimes it throws exception as java.net.UnknownHostException: Host is unresolved: webservername.com:80. I m fetching json response from api.
I m using fetching code as following:
String queryResult = null;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI(archiveQuery));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//HttpResponse response = client.execute(request, new BasicResponseHandler());
try {
queryResult = client.execute(request, new BasicResponseHandler());
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think it's a DNS issue of your server, according to your comments. Sometimes you ping, sometimes you don't, but on your browser it always work? Surely it's a server connectivity issue.
The Answer is really very simple. You need to Restart the emulator.Check out this
Just restart adb, find adb.exe in your adt bundle and double click it. Some shit will happen on command prompt, and there you go, restart your emulator and it should work fine,

Android asynchronus HTTP client problem

I am trying to implement asynchronus http client for Android and I am haveing a trouble with type mismatch:
The method execute(HttpUriRequest) in the type HttpClient is not applicable for the arguments (HttpRequest)
I am doing all based on this tutorial: http://blog.androgames.net/12/retrieving-data-asynchronously/
Have found a type in AsynchronousSender - private HttpRequest request; but I have still problem with above which occurs in:
public void run() {
try {
final HttpResponse response;
synchronized (httpClient) {
response = getClient().execute(request); //<-- here is that problem
}
// process response
wrapper.setResponse(response);
handler.post(wrapper);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Can you suggest anything ?
cheers,
/Marcin
The code snippets on http://blog.androgames.net/12/retrieving-data-asynchronously/ are wrong. To fix it just replace HttpRequest with HttpUriRequest since the method signature is: HttpClient#execute(HttpUriRequest). It shouldn't be any problem since most requests you work with are HttpUriRequest instances.

Categories

Resources