2
package com.yarin.android.Examples_08_01;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
//以Get方式上傳參數
public class Activity03 extends Activity {
private final String DEBUG_TAG = "Activity03";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
TextView mTextView = (TextView) this.findViewById(R.id.TextView_HTTP);
// http address "?par=abcdefg" is the argument to be posted
String httpUrl = "http://192.168.0.100:8080/httpGet.jsp?par=test";
// 獲得的數據
String resultData = "";
URL url = null;
try {
// 構造一個URL對象
url = new URL(httpUrl);
} catch (MalformedURLException e) {
Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null) {
try {
// 使用HttpURLConnection打開連接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 得到讀取的內容(流)
InputStreamReader in = new InputStreamReader(
urlConn.getInputStream());
// 爲輸出創建BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
// 使用循環來讀取獲得的數據
while (((inputLine = buffer.readLine()) != null)) {
// 我們在每一行後面加上一個"\n"來換行
resultData += inputLine + "\n";
}
// 關閉InputStreamReader
in.close();
// 關閉http連接
urlConn.disconnect();
// 設置顯示取得的內容
if (resultData != null) {
mTextView.setText(resultData);
} else {
mTextView.setText("讀取的內容爲NULL");
}
} catch (IOException e) {
Log.e(DEBUG_TAG, "IOException");
}
} else {
Log.e(DEBUG_TAG, "Url NULL");
}
Button button_Back = (Button) findViewById(R.id.Button_Back);
/* 監聽button的事件信息 */
button_Back.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
/* 新建一個Intent對象 */
Intent intent = new Intent();
/* 指定intent要啓動的類 */
intent.setClass(Activity03.this, Activity01.class);
/* 啓動一個新的Activity */
startActivity(intent);
/* 關閉當前的Activity */
Activity03.this.finish();
}
});
}
}
對於上面的代碼,我理解它是如何工作的。它作爲應用程序運行,需要與Web服務器通信。如何製作可以與我的Android手機通信的網絡服務器?
但我不知道如何使這可能是「http://192.168.0.100:8080/httpGet.jsp」的容器的Web服務器。
我做了一些調查。 (1)在Android手機上,i-jetty
,kws
,atieews
可能會有所幫助,但我未能使它們適用於我的目的。
(2)在PC上,tomcat
是一個很好的候選作爲jsp容器。但它提供了localhost:8080
地址,這意味着只有在PC上運行的應用程序才能與之通信。我對嗎?如何讓我的Android手機連接tomcat(在我的電腦上運行)?
(3)有沒有其他想法?
謝謝!
謝謝你的回答!我搜索並找到了一些東西,但需要進一步探索它們。 –
你很好。建立網絡服務器應用程序並不容易。花點時間瞭解你如何正確使用它。嘗試使用JSON,它比SOAP更快。如果我回答了您的問題,請將答案選爲好的答案。請享用。 –
@Miloš通過製作網絡服務器,我們究竟意味着什麼?不,他需要一個Web服務器,並承載他的服務?到底什麼是解決方案? – 2014-08-07 16:45:49