gpt4 book ai didi

android - Android 中的一个简单套接字应用程序需要一些特殊权限才能通过互联网连接吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:41:47 27 4
gpt4 key购买 nike

Android 中的一个简单套接字应用程序需要一些特殊权限才能通过互联网连接吗?

我的代码有什么问题?当它尝试连接到输入文本 IP 或主机时,它总是会出现异常。

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" );
}

}
}

最佳答案

你有吗

<uses-permission android:name="android.permission.INTERNET" /> 

在你的 list 中?在应用程序标签之外。

关于android - Android 中的一个简单套接字应用程序需要一些特殊权限才能通过互联网连接吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6778103/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com