Почему в Java работает отправка запросов, но не работает в Android Studio?
Имеется код на Java для отправки запроса на сервер, написанный на Python. Он работает, но при запуске в Android Studio вылезает ошибка. Рабочий код на Java:
public static int getStructure(String link) throws IOException {
Socket s = new Socket("127.0.0.1", 9090);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
System.out.println(out);
String str = link;
byte buf[] = str.getBytes();
out.write(buf);
int size;
byte buf_out[] = new byte[1024];
while ((size = in.read(buf_out)) != -1) {
System.out.print(new String(buf_out, 0, size));
}
s.close();
return 0;
}
Код сервера на Python:
import socket, json, githubmachine
sock = socket.socket()
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
print('connected:', addr)
while True:
data = conn.recv(1024)
link = data
if not data:
break
conn.send(bytes(json.dumps({"name": "Viktor", "age": 30}), encoding="utf-8"))
conn.close()
Не рабочий код в Android Studio:
public static int getStructure(String link) throws IOException {
Socket s = new Socket("127.0.0.1", 9090);
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
System.out.println(out);
String str = link;
byte buf[] = str.getBytes();
out.write(buf);
int size;
byte buf_out[] = new byte[1024];
while ((size = in.read(buf_out)) != -1) {
System.out.print(new String(buf_out, 0, size));
}
s.close();
return 0;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
textView = (TextView) findViewById(R.id.textView);
blockName = (EditText) findViewById(R.id.editTextTextPersonName);
Button[] twoVertex = new Button[2]; // array that contain from 0 to 2 vertex to draw an edge between it
vertexView = new DrawView(this, 0, 0, 100, 200);
relativeLayout.addView(vertexView);
try {
getStructure("1 ");
} catch (IOException e) {
System.out.println(e.toString());
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nitm">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Nitm">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>