0
我有我的Android模擬器暫時連接到本地計算機。它聯繫PHP併發布要運行的IP地址。然後它迴應一個JSON結果。我想打印結果,但無法讓android屏幕更改。在Android屏幕上打印JSON響應
這裏是我的活動:
public class MainActivity extends Activity implements OnClickListener {
EditText ipAddress;
Button bSearch;
String IP;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> nameValuePairs;
HttpResponse response;
HttpEntity entity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
private void initialize(){
ipAddress = (EditText) findViewById(R.id.IPaddress);
bSearch = (Button) findViewById(R.id.searchBtn);
bSearch.setOnClickListener((OnClickListener) this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://127.0.0.1/myfiles/WorkingVersionVJSON.php");
IP = ipAddress.getText().toString();
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("ipaddress", IP));
try{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()==200){
entity = response.getEntity();
if(entity != null){
InputStream instream = entity.getContent();
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
String rIP = jsonResponse.getString("ipaddress");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
而且PHP
<?php
require("IPQFunctionworkingversionV7.php");
$ipaddress = $_POST["ipaddress"];
$results = array();
$results = getScore($ipaddress);
echo json_encode($results);
?>
PHP的工作時,我在瀏覽器中運行它,並使用HTML張貼到它。我假定線
nameValuePairs.add(new BasicNameValuePair("ipaddress", IP));
帖子到PHP以同樣的方式,因爲IP應該是什麼的進入對Android的文本框,它的POST在PHP相匹配。
活動編譯並位於模擬器上,所以我假定連接成功。我只需要以能夠讓它顯示在屏幕上的方式解析JSON響應。一旦我有了,我會在佈局上工作。