我有試著找了網路上兩個範例來測試
不過很明顯的都失敗orz
希望版友能給些幫助
這是壹號方法
按鈕按下去之後沒有任何反應
不知道有沒有正確動作
伺服器那邊似乎也沒有紀錄貳號方法
碰到的問題是
按下送出之後
都被連線拒絕
我查了一下可能是
因為沒有加上 <uses-permission android:name="android.permission.INTERNET" />
但是我加上去之後在按鈕按下的同時程式就會崩潰
- public class Main extends Activity implements OnClickListener
- {
- private EditText txtMessage;
- private Button sendBtn;
- private String uriAPI = "http://119.14.80.132/ACT_ID_324";
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- txtMessage = (EditText) findViewById(R.id.editText1);
- sendBtn = (Button) findViewById(R.id.button1);
- if (sendBtn != null)
- {
- sendBtn.setOnClickListener(this);
- }
- }
- @Override
- public void onClick(View v)
- {
- if (v == sendBtn)
- {
- String msg = null;
- if (txtMessage != null)
- {
- msg = txtMessage.getEditableText().toString();
- String result = sendPostDataToInternet(msg);
- if (result != null)
- Toast.makeText(this, result, Toast.LENGTH_LONG).show();
- }
- }
- }
- private String sendPostDataToInternet(String strTxt)
- {
- HttpPost httpRequest = new HttpPost(uriAPI);
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("USX0", strTxt));
- try
- {
- /* 發出HTTP request */
- httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
- /* 取得HTTP response */
- HttpResponse httpResponse = new DefaultHttpClient()
- .execute(httpRequest);
- /* 若狀態碼為200 ok */
- if (httpResponse.getStatusLine().getStatusCode() == 200)
- {
- /* 取出回應字串 */
- String strResult = EntityUtils.toString(httpResponse
- .getEntity());
- // 回傳回應字串
- return strResult;
- }
- } catch (ClientProtocolException e)
- {
- Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_SHORT)
- .show();
- e.printStackTrace();
- } catch (IOException e)
- {
- Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_SHORT)
- .show();
- e.printStackTrace();
- } catch (Exception e)
- {
- Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_SHORT)
- .show();
- e.printStackTrace();
- }
- return null;
- }
- }
複製代碼 |