我正在制作一个需要HttpURLConnection的应用。我在模拟器和我的
上测试了它Optimus S版本2.3.3但是当我在Galaxy S3版本4.1.2上测试它时会自动失败。 LogCat不会显示任何错误。所以我想知道为什么它在Galaxy S3上失败了。
Http Setup
System.setProperty("http.keepAlive", "false");
URL check_url = new URL("http://www.website.com");
HttpURLConnection http = (HttpURLConnection) check_url.openConnection();
http.setConnectTimeout(3000);
http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
http.setRequestMethod("GET");
http.connect();
答案 0 :(得分:0)
某些Android版本(我不知道)需要AsyncTask来建立HTTP连接,因此您必须将代码放在这样的后台线程中。
public void makeSingUp(){
new AsyncTask<Void, Void, Boolean>(){
@Override
protected Boolean doInBackground(Void... params){
//Your code connection
return true;
}
@Override
public void onPostExecute(Boolean result){
//Some message that indicates the connection was finished, or nothing.
}
}.execute();
}
答案 1 :(得分:0)
下载volley lib并添加到您的项目中。教程[link]:http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ public class send_data extends AsyncTask { protected void onPreExecute(){ super.onPreExecute(); mProgressDialog = new ProgressDialog(main.this); mProgressDialog.setCancelable(假); mProgressDialog.setTitle(“请稍等......”); mProgressDialog.show(); } protected String doInBackground(String ... args){
String url = "http://your_url";
try {
ArrayList<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>(
1);
nvp.add(new BasicNameValuePair("key for your data","yourdata"));
String str_responsebody = obj_service.executer(url, nvp);
Log.i("responce", str_responsebody + "===");
return str_responsebody;
} catch (Exception e) {
Log.i("error1", "" + e.toString());
return null;
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
Log.i("result", result);
mProgressDialog.dismiss();
}
} catch (Exception e) {
Log.e("error2", "" + e.toString());
e.printStackTrace();
mProgressDialog.dismiss();
}
}
}