Androidのシンプルなソケットアプリには、インターネットに接続するための特別な権限が必要ですか?Androidのシンプルなソケットアプリには、インターネットに接続するための特別な権限が必要ですか?
私のコードで何が間違っていますか?入力テキストIPまたは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");
}
}
}
これは便利かもしれ呼ばれています! http://stackoverflow.com/questions/8706464/defaulthttpclient-to-androidhttpclientの – chain
可能な重複[JavaソケットにIOException - 許可拒否](http://stackoverflow.com/questions/4074808/java-socket- ioexception-permission-denied) –