Không lấy được chuỗi Json từ Web service bằng code android
Em chào mọi người trong diễn đàn.
Em đang thực hiện một bài tập về lấy dữ liệu từ web service.
Em thực hiên lấy chuỗi json từ localhost xampp.
Chuỗi Json trên localhost em đã thử với http://codebeauty.org, nhưng ở đây em chỉ cần lấy về chuỗi mà chưa cần parser Json.
Nhưng không hiểu sao không nhận được giá trị trả về, em thực hiện code theo hướng dẫn. Và cũng thử một số code theo Stack Overflow.
code Android:
public class MainActivity extends AppCompatActivity {
Button btnGet;
TextView txtJson;
ProgressDialog pd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGet = (Button) findViewById(R.id.btnGet);
txtJson = (TextView) findViewById(R.id.txtJson);
final String duongdan = "http://192.168.0.102:81/Weblazada/loaisanpham.php?maloaicha=0";
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JsonTask().execute(duongdan);
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"
");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
Em muốn hỏi là có phải vấn đề tại đường dẫn không? Em đã load thử đường dẫn trong code trên máy android thật và có load được chuỗi json. Nhưng em không lấy được json bằng code android.
Em cảm ơn mọi người.
Chúc mọi người làm việc hiệu quả ạ.
Thấy cũng bình thường, chú getReponseCode xem nó trả về gi?
example: