現在、ローカルで実行しているphpスクリプトを介してmysqlデータを取得するAndroidアプリに取り組んでいますが、スクリプトに接続できないことを示すhttpconnectionエラーが発生し続けます(http://127.0.0.1/regions .php)ローカルサーバーで実行しています。コードは次のとおりです。
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.*;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import com.paypal.android.MEP.*;
public class ShoppingCartActivity extends Activity {
JSONArray jArray;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
InputStream is = null;
StringBuilder sb = null;
String result = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/regions.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();//this holds returned content
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parsing data
int reg_id;
String reg_name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
reg_id=json_data.getInt("RegionID");
reg_name=json_data.getString("RegionName");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Regions Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
}
これが私が投稿しているphpスクリプトです:
<?php
$conn = mysql_connect("127.0.0.1","","");
mysql_select_db("thebigchoice") or die(mysql_error());
$query = mysql_query("SELECT * FROM REGIONS WHERE RegionName LIKE 's%'", $conn) or die(mysql_error());
while($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
print json_encode($data);
mysql_close($conn);
?>