馬上加入Android 台灣中文網,立即免費下載應用遊戲。
您需要 登錄 才可以下載或查看,沒有帳號?註冊
x
小妹最近剛學android java,
正在學習android java 與 PHP 通訊,
各位高手能幫忙檢驗一下哪裡有錯誤嗎 ?
能執行,但卻傳不回東西.......
程式碼如下 ...
public class MainActivity extends ActionBarActivity {
private Button button;
private TextView textView2;
private TextView textView3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView2 = (TextView) findViewById(R.id.textView2);
textView3 = (TextView) findViewById(R.id.textView3);
button.setOnClickListener(btnListener);
}
private Button.OnClickListener btnListener =
new Button.OnClickListener() {
public void onClick(View v) {
runOnUiThread(new Runnable() {
public void run() {
String url = "http://127.0.0.1/~USER/url.php";
HashMap<String, String> map = new HashMap();
map.put("userName", "KarLina");
String str = executePost(url, map);
textView2.setText(str);
textView3.setText("POST DONE");
}
});
}
};
public String executePost(String requestURL,HashMap<String,String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response+=line;
}
}else{
response="";
throw new Exception(responseCode+"");
}
}catch (Exception e) {
e.printStackTrace();
}
return response;
}
static String getPostDataString(HashMap<String, String> params) throws
UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String>entry:params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
**PHP
<?php
echo $_REQUEST["userName"];
?>
在想是否是 textview2 setText()的問題,但打getText()一樣是錯誤的
拜託大大可否幫幫忙 :( 感謝批評指教。
|

|