How to fix "unexpected null receiver" in android - android

There is a python server in my pepper robot and it works fine on the machine. I use putty to start the server and ncat to send my command and there is no problem at all.
In my Connection fragment I need to create a channel to send an ssh command to robot to start the server and then I need to create socket to the server. Then when I send a package to connect server to the application with this command: {'command': '< SYS_CONNECT>'}
In response server should send some information about robot like name, battery level and etc. BUT i just got null from server.
There is application used to run in anroid 5.1 and some years before. Now I deceided to create new application and import some class and components from old application.
private boolean connect(){
state = ConnectionState.CONNECTION_INIT;
for( String h : hostAdresses ){
try{
host = h;
// create socket
socket = new Socket( InetAddress.getByName(host).getHostAddress(), port );
socket.setSoTimeout(defaultReadTimeout);
in = new BufferedReader( new InputStreamReader( new BufferedInputStream(socket.getInputStream()) ) );
out = socket.getOutputStream();
// try to connect
int tries = connectionMaxTries;
while(!stop && socket != null && state == ConnectionState.CONNECTION_INIT && tries > 0) {
// send connection request
DataRequestPackage p = new DataRequestPackage(
PepperCommands.SYS_CONNECT,
new String[0]);
String data = gson.toJson(p);
// wait for data
//data = in.readLine();
try {
out.write(data.getBytes());
Log.w(TAG, "Sending data =" + data);
StringBuilder sb = new StringBuilder();
while ((data = in.readLine()) != null) {
sb.append(data);
Log.d(TAG, "loop data");
}
data = sb.toString();
} catch (Exception e) {
Log.d(TAG, "error on reading data");
}
Log.w(TAG, "Receiving data = " + data);
Log.w(TAG, "in.readLine(), data = " + in.readLine());
DataResponsePackage response = gson.fromJson(data, DataResponsePackage.class);
if( response.request.command == PepperCommands.SYS_CONNECT
&& response.requestSuccessfull){
state = ConnectionState.CONNECTION_ESTABLISHED;
notifyDataRecievedListeners(response);
return true;
}
tries--;
}
}catch(UnknownHostException e){
state = ConnectionState.CONNECTION_UNKNOWN_HOST;
Log.w(TAG, "Host unknown " + host);
MainActivity.getInstance().runOnUiThread( new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.getInstance().getApplicationContext(),
R.string.net_unknown_host, Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
state = ConnectionState.CONNECTION_ESTABLISHED_FAILED;
Log.w(TAG, "IO Exception on connnection with " + host + ":" + port);
}
}
return false;
}
Tries to start remote server using ssh.
/**
* Tries to start remote server using ssh.
* #return {#code true} if server started, {#code false} otherwise.
*/
private boolean sshServerStart(){
// show message
MainActivity.getInstance().runOnUiThread( new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.getInstance().getApplicationContext(),
R.string.net_try_server_start, Toast.LENGTH_SHORT).show();
}
});
// send command
String[] vCommands = new String[]{ SSH_COMMAND_SERVER_START };
if( sendSSHCommands( vCommands ).size() > 0 ){
// wait a few seconds for server to start
try {
Thread.sleep(5000);
} catch (InterruptedException e) {}
return true;
}
return false;
}
Connecting to ssh server
/**
* Connecting to ssh server
* #return {#code true} if successful connected, {#code false} otherwise.
*/
private Session connectSSH(){
for( String host : hostAdresses ){
try {
// get user information
SharedPreferences vPreferences = MainActivity.getPreferences();
String vUser = vPreferences.getString(PREFERENCES_SSH_USER, "nao");
String vPassword = vPreferences.getString(PREFERENCES_SSH_PASSWORD, "nao");
if( mUseCustomLoginData ){
vUser = mSSHUser;
vPassword = mSSHPassword;
}
// create session
Session vSession = mSSH.getSession(vUser,
InetAddress.getByName(host).getHostAddress().toString(),
22 );
vSession.setPassword( vPassword );
// avoid asking for key auth
Properties vProperties = new Properties();
vProperties.put("StrictHostKeyChecking", "no");
vSession.setConfig(vProperties);
try{
// connect to ssh server
vSession.connect();
} catch( JSchException err ){
if( err.getMessage().contains("Auth fail") ){
// ask for custom login data
if( askForCustomLoginData() ){
vSession = connectSSH();
} else {
return null;
}
} else {
System.out.println("EXCEPTION: " + err.getMessage());
err.printStackTrace();
}
}
return vSession;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (JSchException e) {
e.printStackTrace();
}
}
return null;
}
I expect on this code response.request.command return SYS_CONNECT and response.requestSuccessfull return true on this line but I got unexpected null response
if( response.request.command == PepperCommands.SYS_CONNECT && response.requestSuccessfull){

Related

Permission denied when tried to connect to an SSH server

I have installed a python server on my robot and also create a socket to robot successfully. Everything is looking fine but when I want to create a channel I have an error that says:
sending naocom/start.sh
W/System.err: bash: naocom/start.sh: Permission denied
here is where I tried to start connection and start python server with
public Map<String, Integer> sendSSHCommands(String[] aCommands, String... aInput){
// Connect to ssh server
Session vSession = connectSSH();
Map<String, Integer> vExitStatus = new HashMap<String, Integer>();
if( vSession != null){
// execute commands
for( int i=0; i < aCommands.length; i++ ){
String cmd = aCommands[i];
try{
// open channel
Channel vChannel = vSession.openChannel("naocom/start.sh");
ChannelExec vChannelExec = (ChannelExec) vChannel;
OutputStream vOutStream = vChannel.getOutputStream();
vChannelExec.setCommand(cmd);
vChannelExec.setOutputStream(System.out);
vChannelExec.setErrStream(System.err);
// connect
Log.i(TAG, "sending " + cmd);
vChannel.connect();
// get user information
SharedPreferences vPreferences = MainActivity.getPreferences();
// wait for command to complete
while( !vChannel.isClosed() ){
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
};
// add exit status
vExitStatus.put( cmd, vChannel.getExitStatus() );
vOutStream.close();
vChannel.disconnect();
} catch(JSchException e){
Log.e(TAG, e.getMessage());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
// close ssh connection
closeSSH(vSession);
}
return vExitStatus;
}
when I debuged my code I found it happend when start(); in Channel.java called
public void connect() throws JSchException{
connect(0);
}
public void connect(int connectTimeout) throws JSchException{
this.connectTimeout=connectTimeout;
try{
sendChannelOpen();
start(); //here i have an error
}
catch(Exception e){
connected=false;
disconnect();
if(e instanceof JSchException)
throw (JSchException)e;
throw new JSchException(e.toString(), e);
}
}

550 Error on Uploading Files using FTP over SSL Android

I'm using Apache commonsnet library for FTP. I'm able to create the folders in FTP server. But whenever I storeFile it's failing and returning me 550 error.
FTPUpload
private boolean ftpUpload(String remoteFilePath) {
FTPSClient ftpsClient = null;
try {
ftpsClient = new FTPSClient("SSL", true);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
FileInputStream fis;
boolean result = false;
try {
if (ftpsClient != null) {
ftpsClient.setConnectTimeout(10000);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(null, null);
KeyManager km = kmf.getKeyManagers()[0];
ftpsClient.setKeyManager(km);
ftpsClient.connect(InetAddress.getByName(getString(R.string.ftp_hostname)), 990);
boolean isLoggedIn = ftpsClient.login(getString(R.string.ftp_username), getString(R.string.ftp_password));
if (isLoggedIn) {
// On Successful login
ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpsClient.enterLocalPassiveMode();
ftpsClient.setBufferSize(1000);
// Check remotePath exists else create folders
int index = remoteFilePath.lastIndexOf("/");
String remoteDir = null;
if (index != -1)
remoteDir = remoteFilePath.substring(0, index);
if (remoteDir != null)
/**
* changeWorkingDirectory returns whether the specified directory exist or not.
* If not exist in remote, create folders
*/
if (!ftpsClient.changeWorkingDirectory(remoteDir)) {
if (makeDirectories(ftpsClient, remoteDir))
ftpsClient.changeWorkingDirectory(remoteFilePath);
else
Log.e(this.getClass().getSimpleName(), "remote path is not available");
} else
ftpsClient.changeWorkingDirectory(remoteFilePath);
//Testing
File localFilePath = new File(Environment.getExternalStorageDirectory() + "/qwerty.png");
ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
try{
int reply = ftpsClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpsClient.disconnect();
Log.e(this.getClass().getSimpleName(), "Connection Refused by server");
return false;
}
} catch(Exception e) {
e.printStackTrace();
}
// Get the stream of the file
String testName = localFilePath.getName();
fis = new FileInputStream(localFilePath);
// Upload file to the ftp server
result = ftpsClient.storeFile(testName, fis);
fis.close();
Log.i(this.getClass().getSimpleName(), "FTP Store Result " + result);
if (result) {
result = true;
} else {
result = false;
}
} else {
Log.e(this.getClass().getSimpleName(), "Login Fail!");
result = false;
}
// logout from ftp server
ftpsClient.logout();
}
} catch (Exception e) {
Log.e(this.getClass().getSimpleName(), "FTP Exception!");
result = false;
}
return result;
}
It's connecting, authenticating, created new folder but storingFile/getReplyCode always returns 550. What is wrong here? I have removed KeyManagerFactory also but no luck.

Android socket connection loses after app being idle for some time

My application listens to a socket. The application is connected to the socket using the following method.
public void connect() {
this.connectionStatus = CONNECT_STATUS_CONNECTING;
Log.v(AppConstants.DEBUG_TAG, userId + " : Connecting to Server");
if (mThread != null && mThread.isAlive()) {
return;
}
mThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Log.v(AppConstants.DEBUG_TAG, userId + " : Thread Action Started");
String secret = createSecret();
int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getScheme().equals("wss") ? 443 : 80);
String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
if (!TextUtils.isEmpty(mURI.getQuery())) {
path += "?" + mURI.getQuery();
}
String originScheme = mURI.getScheme().equals("wss") ? "https" : "http";
URI origin = new URI(originScheme, "//" + mURI.getHost(), null);
SocketFactory factory = mURI.getScheme().equals("wss") ? getSSLSocketFactory() : SocketFactory.getDefault();
mSocket = factory.createSocket(mURI.getHost(), port);
PrintWriter out = new PrintWriter(mSocket.getOutputStream());
out.print("GET " + path + " HTTP/1.1\r\n");
out.print("Upgrade: websocket\r\n");
out.print("Connection: Upgrade\r\n");
out.print("Host: " + mURI.getHost() + "\r\n");
out.print("Origin: " + origin.toString() + "\r\n");
out.print("Sec-WebSocket-Key: " + secret + "\r\n");
out.print("Sec-WebSocket-Version: 13\r\n");
if (mExtraHeaders != null) {
for (NameValuePair pair : mExtraHeaders) {
out.print(String.format("%s: %s\r\n", pair.getName(), pair.getValue()));
}
}
out.print("\r\n");
out.flush();
HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(mSocket.getInputStream());
// Read HTTP response status line.
StatusLine statusLine = parseStatusLine(readLine(stream));
if (statusLine == null) {
Log.v(AppConstants.DEBUG_TAG, "Received no reply from server.");
throw new HttpException("Received no reply from server.");
} else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
// Read HTTP response headers.
String line;
boolean validated = false;
while (!TextUtils.isEmpty(line = readLine(stream))) {
Header header = parseHeader(line);
if (header.getName().equals("Sec-WebSocket-Accept")) {
String expected = createSecretValidation(secret);
String actual = header.getValue().trim();
if (!expected.equals(actual)) {
Log.v(AppConstants.DEBUG_TAG, "Bad Sec-WebSocket-Accept header value.");
throw new HttpException("Bad Sec-WebSocket-Accept header value.");
}
validated = true;
}
}
if (!validated) {
Log.v(AppConstants.DEBUG_TAG, "No Sec-WebSocket-Accept header.");
throw new HttpException("No Sec-WebSocket-Accept header.");
}
onConnect();
Log.v(AppConstants.DEBUG_TAG, userId + " : Thread should be connected by now");
// Now decode websocket frames.
mParser.start(stream);
} catch (EOFException ex) {
Log.d(AppConstants.DEBUG_TAG, "WebSocket EOF!", ex);
onDisconnect(0, "EOF");
} catch (SSLException ex) {
// Connection reset by peer
Log.d(AppConstants.DEBUG_TAG, "Websocket SSL error!", ex);
onDisconnect(0, "SSL");
} catch (Exception ex) {
onError(ex);
}
}
});
Log.v(AppConstants.DEBUG_TAG, userId + " : Thread about to be started");
mThread.start();
}
Here the problem is when I leave the application for 15 or more idle, the connection automatically closes and app becomes unusable.What is the reason behind it and how to resolve this?
Probably, it is the server that closes the idle connection. Send Ping (or Pong) periodically to keep the connection.
BTW, I guess your code is based on a certain open-source WebSocket library. If so, note that it is not of commercial quality. It does not perform even the closing handshake on disconnect().

How to get a working HttpsUrlConnection with Steam Web API?

im currently trying to implement the Steam Web API using the given code in the following repository -> https://github.com/Overv/SteamWebAPI/blob/master/SteamAPISession.cs into my Android app and im getting different exceptions dependend on using the given wep api ip ( 63.228.223.110 ) or the adress ( https://api.steampowered.com/ ) itself.
my code actually looks like this in the given method when building up a connection to the web api:
private String steamRequest( String get, String post ) {
final int MAX_RETRIES = 3;
int numberOfTries = 0;
HttpsURLConnection request = null;
while(numberOfTries < MAX_RETRIES) {
if (numberOfTries != 0) {
Log.d(TAG, "Retry -> " + numberOfTries);
}
try {
request = (HttpsURLConnection) new URL("https://api.steampowered.com/" + get).openConnection(); //or 63.228.223.110/ ???
SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
String host = "api.steampowered.com";
int port = 443;
int header = 0;
socketFactory.createSocket(new Socket(host, port), host, port, false);
request.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
request.setSSLSocketFactory(socketFactory);
request.setDoOutput(false);
// request.setRequestProperty("Host", "api.steampowered.com:443");
// request.setRequestProperty("Protocol-Version", "httpVersion");
request.setRequestProperty("Accept", "*/*");
request.setRequestProperty("Accept-Encoding", "gzip, deflate");
request.setRequestProperty("Accept-Language", "en-us");
request.setRequestProperty("User-Agent", "Steam 1291812 / iPhone");
request.setRequestProperty("Connection", "close");
if (post != null) {
byte[] postBytes;
try {
request.setRequestMethod("POST");
postBytes = post.getBytes("US-ASCII");
// request.setRequestProperty("Content-Length", Integer.toString(postBytes.length));
request.setFixedLengthStreamingMode(postBytes.length);
request.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(request.getOutputStream());
out.print(post);
out.close();
// DataOutputStream requestStream = new DataOutputStream(request.getOutputStream());
//// OutputStreamWriter stream = new OutputStreamWriter(request.getOutputStream());
//// stream.write(postBytes, 0, postBytes.length);
// requestStream.write(postBytes, 0, postBytes.length);
// requestStream.close();
message++;
} catch (ProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
int statusCode = request.getResponseCode();
InputStream is;
Log.d(TAG, "The response code of the status code is" + statusCode);
if (statusCode != 200) {
is = request.getErrorStream();
Log.d(TAG, String.valueOf(is));
}
// String src = null;
// OutputStreamWriter out = new OutputStreamWriter(request.getOutputStream());
// out.write(src);
// out.close();
Scanner inStream = new Scanner(request.getInputStream());
String response = "";
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
// String src;
// BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
// StringBuilder builder = new StringBuilder();
// while ((src = in.readLine()) != null) {
// builder.append(src);
// }
// String jsonData = builder.toString();
Log.d(TAG, response); //jsonData
// in.close();
return response; //jsonData
} catch (MalformedURLException ex) {
Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_LONG).show();
ex.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (request != null) {
request.disconnect();
}
}
numberOfTries++;
}
Log.d(TAG, "Max retries reached. Giving up on connecting to Steam Web API...");
return null;
}
following exception occurs when using https://api.steampowered.com/ as url:
W/System.err﹕ java.io.FileNotFoundException: https://api.steampowered.com/ISteamOAuth2/GetTokenWithCredentials/v0001
D/OptionsFragment﹕ Failed to log in!
i've really tried and researched on those issues, but i just can't get a solution. If someone got a good hint on helping to solve these exceptions please let me know!
EDIT:
I've researched some more!
Looking up on https://partner.steamgames.com/documentation/webapi#creating the direct ip adress shouldn't be used and therefore only the DNS name itself (for further clarification look on the given link). Hence, looking up on the API interface list itself -> http://api.steampowered.com/ISteamWebAPIUtil/GetSupportedAPIList/v0001/?format=json there doesn't seem to be a given Interface with a method called ISteamOAuth2/GetTokenWithCredentials.(Or not anymore!) Only ISteamUserAuth and ISteamUserOAuth which seem to handle Authentication stuff.
I will update this post again if i should get a working connection and handling with the steam web api.
Cheers!

How to retrieve a file from http server

I have the following web server class found here. I need to write an Android application(client) which can retrieve a file from this server. It would be great if anyone would be able to help me to do it. Thank you.
Server host address is: My-PC/ipaddress
When I execute the client it gives an exception.
java.net.ConnectException: Connection refused: connect
WebServer.Java
import java.io.*;
import java.net.*;
public class WebServer extends Thread {
public WebServer() {
this.start();
}
private void displayString(String string) { //an alias to avoid typing so much!
System.out.println(string);
}
private static final int UMBRA_PORT = 30480;
private static final int ROOM_THROTTLE = 200;
private InetAddress hostAddress;
//this is a overridden method from the Thread class we extended from
public void run() {
//we are now inside our own thread separated from the gui.
ServerSocket serversocket = null;
//To easily pick up lots of girls, change this to your name!!!
displayString("The simple httpserver v. 0000000000\nCoded by Jon Berg" +
"<jon.berg[on server]turtlemeat.com>\n\n");
//Pay attention, this is where things starts to cook!
try {
//print/send message to the guiwindow
displayString("Trying to bind to localhost on port " + Integer.toString(UMBRA_PORT) + "...");
//make a ServerSocket and bind it to given port,
//serversocket = new ServerSocket(port);
}
catch (Exception e) { //catch any errors and print errors to gui
displayString("\nFatal Error:" + e.getMessage());
return;
}
// Attempt to get the host address
try
{
hostAddress = InetAddress.getLocalHost();
}
catch(UnknownHostException e)
{
System.out.println("Could not get the host address.");
return;
}
// Announce the host address
System.out.println("Server host address is: "+hostAddress);
// Attempt to create server socket
try
{
serversocket = new ServerSocket(UMBRA_PORT,0,hostAddress);
}
catch(IOException e)
{
System.out.println("Could not open server socket.");
return;
}
// Announce the socket creation
System.out.println("Socket "+serversocket+" created.");
displayString("OK!\n");
//go in a infinite loop, wait for connections, process request, send response
while (true) {
displayString("\nReady, Waiting for requests...\n");
try {
//this call waits/blocks until someone connects to the port we
//are listening to
Socket connectionsocket = serversocket.accept();
//figure out what ipaddress the client commes from, just for show!
InetAddress client = connectionsocket.getInetAddress();
//and print it to gui
displayString(client.getHostName() + " connected to server.\n");
//Read the http request from the client from the socket interface
//into a buffer.
BufferedReader input =
new BufferedReader(new InputStreamReader(connectionsocket.
getInputStream()));
//Prepare a outputstream from us to the client,
//this will be used sending back our response
//(header + requested file) to the client.
DataOutputStream output =
new DataOutputStream(connectionsocket.getOutputStream());
//as the name suggest this method handles the http request, see further down.
//abstraction rules
http_handler(input, output);
}
catch (Exception e) { //catch any errors, and print them
displayString("\nError:" + e.getMessage());
}
} //go back in loop, wait for next request
}
//our implementation of the hypertext transfer protocol
//its very basic and stripped down
private void http_handler(BufferedReader input, DataOutputStream output) {
int method = 0; //1 get, 2 head, 0 not supported
String http = new String(); //a bunch of strings to hold
String path = new String(); //the various things, what http v, what path,
String file = new String(); //what file
String user_agent = new String(); //what user_agent
try {
//This is the two types of request we can handle
//GET /index.html HTTP/1.0
//HEAD /index.html HTTP/1.0
String tmp = input.readLine(); //read from the stream
String tmp2 = new String(tmp);
tmp.toUpperCase(); //convert it to uppercase
if (tmp.startsWith("GET")) { //compare it is it GET
method = 1;
} //if we set it to method 1
if (tmp.startsWith("HEAD")) { //same here is it HEAD
method = 2;
} //set method to 2
if (method == 0) { // not supported
try {
output.writeBytes(construct_http_header(501, 0));
output.close();
return;
}
catch (Exception e3) { //if some error happened catch it
displayString("error:" + e3.getMessage());
} //and display error
}
//}
//tmp contains "GET /index.html HTTP/1.0 ......."
//find first space
//find next space
//copy whats between minus slash, then you get "index.html"
//it's a bit of dirty code, but bear with me...
int start = 0;
int end = 0;
for (int a = 0; a < tmp2.length(); a++) {
if (tmp2.charAt(a) == ' ' && start != 0) {
end = a;
break;
}
if (tmp2.charAt(a) == ' ' && start == 0) {
start = a;
}
}
path = tmp2.substring(start + 2, end); //fill in the path
}
catch (Exception e) {
displayString("errorr" + e.getMessage());
} //catch any exception
//path do now have the filename to what to the file it wants to open
displayString("\nClient requested:" + new File(path).getAbsolutePath() + "\n");
FileInputStream requestedfile = null;
try {
//try to open the file,
requestedfile = new FileInputStream(path);
}
catch (Exception e) {
try {
//if you could not open the file send a 404
output.writeBytes(construct_http_header(404, 0));
//close the stream
output.close();
}
catch (Exception e2) {}
displayString("error" + e.getMessage());
} //print error to gui
//happy day scenario
try {
int type_is = 0;
//find out what the filename ends with,
//so you can construct a the right content type
if (path.endsWith(".zip") ) {
type_is = 3;
}
if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {
type_is = 1;
}
if (path.endsWith(".gif")) {
type_is = 2;
}
if (path.endsWith(".ico")) {
type_is = 4;
}
if (path.endsWith(".xml")) {
type_is = 5;
}
//write out the header, 200 ->everything is ok we are all happy.
output.writeBytes(construct_http_header(200, 5));
//if it was a HEAD request, we don't print any BODY
if (method == 1) { //1 is GET 2 is head and skips the body
byte [] buffer = new byte[1024];
while (true) {
//read the file from filestream, and print out through the
//client-outputstream on a byte per byte base.
int b = requestedfile.read(buffer, 0,1024);
if (b == -1) {
break; //end of file
}
output.write(buffer,0,b);
}
//clean up the files, close open handles
}
output.close();
requestedfile.close();
}
catch (Exception e) {}
}
//this method makes the HTTP header for the response
//the headers job is to tell the browser the result of the request
//among if it was successful or not.
private String construct_http_header(int return_code, int file_type) {
String s = "HTTP/1.0 ";
//you probably have seen these if you have been surfing the web a while
switch (return_code) {
case 200:
s = s + "200 OK";
break;
case 400:
s = s + "400 Bad Request";
break;
case 403:
s = s + "403 Forbidden";
break;
case 404:
s = s + "404 Not Found";
break;
case 500:
s = s + "500 Internal Server Error";
break;
case 501:
s = s + "501 Not Implemented";
break;
}
s = s + "\r\n"; //other header fields,
s = s + "Connection: close\r\n"; //we can't handle persistent connections
s = s + "Server: SimpleHTTPtutorial v0\r\n"; //server name
switch (file_type) {
//plenty of types for you to fill in
case 0:
break;
case 1:
s = s + "Content-Type: image/jpeg\r\n";
break;
case 2:
s = s + "Content-Type: image/gif\r\n";
break;
case 3:
s = s + "Content-Type: application/x-zip-compressed\r\n";
break;
case 4:
s = s + "Content-Type: image/x-icon\r\n";
case 5:
s = s + "Content-Type: text/xml\r\n";
break;
default:
s = s + "Content-Type: text/html\r\n";
break;
}
////so on and so on......
s = s + "\r\n"; //this marks the end of the httpheader
//and the start of the body
//ok return our newly created header!
return s;
}
}
Client.Java
public class WatchMeManagerClient {
private static Socket socket;
private static PrintWriter printWriter;
public static void main(String[] args) throws Exception {
try {
URL url;
URLConnection urlConn;
DataInputStream dis;
url = new URL("http://ipaddress/xml/userGroup.xml");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
dis = new DataInputStream(urlConn.getInputStream());
String s;
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
dis.close();
}
catch (MalformedURLException mue) {
System.out.println(mue.toString());
} catch (IOException ioe) {
System.out.println(ioe.toString());
}
}
}
When I run the code on PC it works. But when I try to execute it on the Android Device it gives following errors.
Such problems are either due to one of the following:
The port is wrong
Firewall is stopping it.
Using Sockets require the following permission which I think you are missing:
<uses-permission android:name="android.permission.INTERNET" />
Did you allow internet access in your manifest?
<uses-permission android:name="android.permission.INTERNET"/>

Categories

Resources