1
正如在標題中所述,我運行我的簡單應用程序時出現問題,該應用程序會在我的手機上發出http請求。在模擬器上它可以很好地工作,但在手機上它不能下載所需的字符串。http請求在模擬器中運行,但不在電話上運行
public class MainActivity extends AppCompatActivity {
Button btn;
public String uzmiLokacije()
{
String url_all_products = "http://www.parkingpmf.co.nf/db_get_all.php";
HttpURLConnection urlConnection = null;
String res = "";
try {
URL url = new URL(url_all_products);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
//String res = "";
while((line=reader.readLine()) != null)
{
res = res + line;
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally{
urlConnection.disconnect();
return res;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener(
){
@Override
public void onClick(View v) {
String ans = uzmiLokacije();
Toast.makeText(getApplicationContext(), ans, Toast.LENGTH_LONG).show();
}
});
}
}
任何提示,爲什麼會出現這種情況? 我在清單中加入了這個:
<uses-permission android:name="android.permission.INTERNET" />
P.我正在使用Android Studio
您是否嘗試過在此設備上的Web瀏覽器中訪問該頁面?此外,您需要將此網絡I/O移至後臺線程,因爲您可能正在使用「NetworkOnMainThreadException」崩潰。 – CommonsWare
我已經嘗試在瀏覽器中打開,是的它的工作原理。你能解釋一下如何去做,因爲到現在爲止我還沒有做任何有關後臺線程的事情? 我會嘗試捕捉異常現在 –
請提供一些更多的信息,以幫助我們,如你的手機,它的Android版本等... –