這裏是我的代碼,我嘗試連接到服務器的數據庫,但給人的異常socketexception網絡NT可達但它工作本地主機請幫助我笏是DIS代碼連接到服務器的數據庫和pasrse數據usind JSON解析器
package com.example.test2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
//import android.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
//import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultView = (TextView) findViewById(R.id.result);
//StrictMode.enableDefaults();
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
Toast.makeText(getApplicationContext() , "1" ,Toast.LENGTH_SHORT).show();
HttpPost httppost = new HttpPost("http://localhost/xampp/connect.php");
String str=httppost.toString();//YOUR PHP SCRIPT ADDRESS
Toast.makeText(getApplicationContext() , str ,Toast.LENGTH_LONG).show();
HttpResponse response = httpclient.execute(httppost);
Toast.makeText(getApplicationContext() , "3" ,Toast.LENGTH_SHORT).show();
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"ID : "+json.getString("id")+" \nNAME : "+json.getString("name")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}
大問題
即使我已經取得互聯網許可仍然需要任何權限
不能在真正的服務器上工作,但在本地主機上工作?你能給我們真正的服務器鏈接嗎?也許問題是在真正的服務器 –
有什麼錯誤? – Exceptional
你有你自己的域名? – Exceptional