Reputation: 53
A simple socket app in Android needs some special permissions to connect through the internet?
Whats wrong with my code? It always get Exceptions when it tryes to connect to input text IP, or HOST.
package What.HTTPServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class WhatHTTPServerActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
TextView text = (TextView)findViewById(R.id.textView4);
EditText textField = (EditText) findViewById(R.id.editText1);
if (textField.getText().toString().length() > 3)
{
String host = textField.getText().toString();
String retorno = "";
text.setTextColor(0xff0000ff);
text.setText("Connecting...");
try {
Socket s = new Socket(host, 80);
//outgoing stream redirect to socket
OutputStream out = s.getOutputStream();
PrintWriter output = new PrintWriter(out);
// send an HTTP request to the web server
output.println("GET / HTTP/1.1");
output.println("Host: " + host + ":80");
output.println("Connection: Close");
output.println();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
// read the response
boolean loop = true;
StringBuilder sb = new StringBuilder(8096);
while (loop) {
if (in.ready()) {
int i = 0;
while (i != -1) {
i = in.read();
sb.append((char) i);
}
loop = false;
}
}
retorno = sb.toString();
//Close connection
s.close();
text.setTextColor(0xff0000ff);
text.setText("Your server runs: \n"
+ retorno );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
text.setTextColor(0xffff0000);
text.setText("Error! The Host or IP is unknown." );
} catch (IOException e) {
// TODO Auto-generated catch block
text.setTextColor(0xffff0000);
text.setText("Unknown error. Check your internet connection!" );
}
} else {
text.setTextColor(0xffff0000);
text.setText("Error! Please type your host or IP" );
}
}
}
Upvotes: 4
Views: 10871
Reputation: 4430
Any internet access from your application requires the internet acces permisison.
The permission you want is called "INTERNET"
Upvotes: 0
Reputation: 8225
Do you have
<uses-permission android:name="android.permission.INTERNET" />
in your manifest? Outside the application tags.
Upvotes: 6