안 드 로 이 드 의 세 가지 네트워크 통신 방식 에 대해 이야기 하 다.
13034 단어 android네트워크 통신 방식
1.표준 자바 인터페이스
java.net.*는 스 트림,패 킷 소켓(socket),인터넷 프로 토 콜,흔 한 Http 처리 등 인터넷 과 관련 된 클래스 를 제공 합 니 다.예 를 들 어 URL 생 성,URLConnection/HttpURLConnection 대상,링크 매개 변수 설정,서버 연결,서버 에 데이터 쓰기,서버 에서 데이터 읽 기 등 통신.이것 은 자바 네트워크 프로 그래 밍 에서 모두 관련 되 어 있 습 니 다.우 리 는 간단 한 socket 프로 그래 밍 을 보고 서버 가 클 라 이언 트 정 보 를 전송 하 는 것 을 실현 합 니 다.
서버:
public class Server implements Runnable{
@Override
public void run() {
Socket socket = null;
try {
ServerSocket server = new ServerSocket(18888);
//
while(true){
System.out.println("start...");
//
socket = server.accept();
System.out.println("accept...");
//
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = in.readLine();
// ,
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println("Server:" + message);
//
in.close();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if (null != socket){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//
public static void main(String[] args){
Thread server = new Thread(new Server());
server.start();
}
}
클 라 이언 트,MainActivity
public class MainActivity extends Activity {
private EditText editText;
private Button button;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText)findViewById(R.id.editText1);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Socket socket = null;
String message = editText.getText().toString()+ "\r
" ;
try {
// socket, : localhost 127.0.0.1,Android localhost
socket = new Socket("<span style="font-weight: bold;">10.0.2.2</span>",18888);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter
(socket.getOutputStream())),true);
//
out.println(message);
//
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = in.readLine();
if (null != msg){
editText.setText(msg);
System.out.println(msg);
}
else{
editText.setText("data error");
}
out.close();
in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
if (null != socket){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}
레이아웃 파일:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<EditText android:layout_width="match_parent" android:id="@+id/editText1"
android:layout_height="wrap_content"
android:hint="input the message and click the send button"
></EditText>
<Button android:text="send" android:id="@+id/button1"
android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
시작 서버:
javac com/test/socket/Server.java
java com.test.socket.Server
클 라 이언 트 실행:결 과 는 그림 과 같다.
메모:서버 와 클 라 이언 트 가 연결 할 수 없 는 이 유 는 다음 과 같 습 니 다.
네트워크 에 접근 할 수 있 는 권한 이 없습니다:
IP 주소 사용:10.0.2.2
시 뮬 레이 터 는 프 록 시 를 설정 할 수 없습니다.
2。아파 치 인터페이스
대부분의 프로그램 에서 JDK 자체 가 제공 하 는 네트워크 기능 이 턱 없 이 부족 하 다.이 때 는 Android 가 제공 하 는 Apache HttpClient 가 필요 하 다.이것 은 오픈 소스 프로젝트 로 기능 이 더욱 완선 되 고 클 라 이언 트 의 Http 프로 그래 밍 에 효율 적 이 고 최신 이 며 기능 이 풍부 한 공구 꾸러미 지원 을 제공 합 니 다.
다음은 HttpClient 를 사용 하여 안 드 로 이 드 클 라 이언 트 에서 웹 을 방문 하 는 방법 을 간단 한 예 로 보 겠 습 니 다.
우선,당신 의 기계 에 웹 애플 리 케 이 션 my app 을 구축 하려 면 아주 간단 한 http.jsp 만 있 습 니 다.
내용 은 다음 과 같다.
<%@page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title>
Http Test
</title>
</head>
<body>
<%
String type = request.getParameter("parameter");
String result = new String(type.getBytes("iso-8859-1"),"utf-8");
out.println("<h1>" + result + "</h1>");
%>
</body>
</html>
그리고 Android 클 라 이언 트 를 실현 합 니 다.각각 post,get 방식 으로 my app 에 접근 합 니 다.코드 는 다음 과 같 습 니 다.레이아웃 파일:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:gravity="center"
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button android:text="get" android:id="@+id/get" android:layout_width="match_parent" android:layout_height="wrap_content"></Button>
<Button android:text="post" android:id="@+id/post" android:layout_width="match_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>
자원 파일:strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello"> </string>
<string name="app_name">Http Get</string>
</resources>
주 활동:
public class MainActivity extends Activity {
private TextView textView;
private Button get,post;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
get = (Button)findViewById(R.id.get);
post = (Button)findViewById(R.id.post);
//
get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// : ip 127.0.0.1 localhost,Android localhost
String uri = "http://192.168.22.28:8080/myapp/http.jsp?parameter= Get ";
textView.setText(get(uri));
}
});
//
post.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String uri = "http://192.168.22.28:8080/myapp/http.jsp";
textView.setText(post(uri));
}
});
}
/**
* get , web
* @param uri web
* @return
*/
private static String get(String uri){
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(uri);
try {
// ,
HttpResponse response = client.execute(request);
//
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
sb = new StringBuffer();
String line = "";
String NL = System.getProperty("line.separator");
while((line = reader.readLine()) != null){
sb.append(line);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
if (null != reader){
reader.close();
reader = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != sb){
result = sb.toString();
}
return result;
}
/**
* post , web
* @param uri web
* @return
*/
private static String post(String uri){
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(uri);
//
List<NameValuePair> params = new ArrayList<NameValuePair>();
//
params.add(new BasicNameValuePair("parameter"," Post "));
try {
//
HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8");
//
request.setEntity(entity);
//
HttpResponse response = client.execute(request);
//
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
System.out.println("post success");
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
sb = new StringBuffer();
String line = "";
String NL = System.getProperty("line.separator");
while((line = reader.readLine()) != null){
sb.append(line);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
try {
//
if (null != reader){
reader.close();
reader = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != sb){
result = sb.toString();
}
return result;
}
}
실행 결 과 는 다음 과 같 습 니 다.3.android.net 프로 그래 밍:
이 가방 의 클래스 를 사용 하여 안 드 로 이 드 특유 의 네트워크 프로 그래 밍 을 자주 합 니 다.예 를 들 어 와 이 파이 방문,안 드 로 이 드 인터넷 정보 방문,메 일 등 기능 입 니 다.여 기 는 자세히 말 하지 않 는 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Kotlin의 기초 - 2부지난 글에서는 Kotlin이 무엇인지, Kotlin의 특징, Kotlin에서 변수 및 데이터 유형을 선언하는 방법과 같은 Kotlin의 기본 개념에 대해 배웠습니다. 유형 변환은 데이터 변수의 한 유형을 다른 데이터...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.