在Android上测试与服务器的连接
我想测试与本地主机(或任何URL)的连接,我编写了一个简单的代码进行测试,我添加了所需的权限以显示,但函数仍然返回“false” 这是我的密码:在Android上测试与服务器的连接,android,sql-server,testing,server,connection,Android,Sql Server,Testing,Server,Connection,我想测试与本地主机(或任何URL)的连接,我编写了一个简单的代码进行测试,我添加了所需的权限以显示,但函数仍然返回“false” 这是我的密码: import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.net.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
String adrs = "http://wwww.google.com";
int time = 10000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
isConnectedToServer(adrs,time);
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isConnectedToServer(adrs,time) == true) { Toast.makeText(getBaseContext(),"Connecté !",Toast.LENGTH_LONG).show();}
else {Toast.makeText(getBaseContext(),"Connexion perdue",Toast.LENGTH_LONG).show();}
isConnectedToServer(adrs,time);
}
});
}
public boolean isConnectedToServer(String url, int timeout) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(timeout);
connection.connect();
Toast.makeText(getBaseContext(),"Connecté !",Toast.LENGTH_LONG).show();
return true;
} catch (Exception e) {
// Handle your exceptions
Toast.makeText(getBaseContext(),"Connexion perdue",Toast.LENGTH_LONG).show();
return false;
}
}
}
这是我的舱单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fisher.testconnection">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
在项目中删除此类,更改url并执行任务以获取服务器的网络速度和连接状态
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class NetworkSpeedCheckTask extends AsyncTask<Void, Void, String> {
private static final int TIMEOUT = 30000;
/**
* @param networkSped
*/
public NetworkSpeedCheckTask(TextView networkSped, Context context) {
this.networkSped = networkSped;
this.context = context;
}
String linkSpeed3G = "0 Kb/s";
TextView networkSped;
private Context context;
/**
* Before starting background do some work.
*/
@Override
protected void onPreExecute() {
if (null != networkSped)
networkSped.setText("fetching");
}
@Override
protected String doInBackground(Void... params) {
try {
long startTime = System.nanoTime();
HttpGet httpRequest;
httpRequest = new HttpGet(new URL("Http://Google.com").toURI());
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT);
HttpClient httpClient = new DefaultHttpClient(httpParams);
HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
long endTime = System.nanoTime();
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
// You can re-check the size of your file
final long contentLength = bufHttpEntity.getContentLength();
linkSpeed3G = internetSpeed((endTime - startTime), contentLength, false);
// Bandwidth : size(KB)/time(s)
float bandwidth = contentLength / ((endTime - startTime) * 1000);
Log.d("NetworkManger", "-----------[BENCHMARK] Dowload time :" + (endTime - startTime) + " ms");
// Log
} catch (MalformedURLException e) {
linkSpeed3G = "Failure";
e.printStackTrace();
} catch (URISyntaxException e) {
linkSpeed3G = "Failure";
e.printStackTrace();
} catch (ClientProtocolException e) {
linkSpeed3G = "Failure";
e.printStackTrace();
} catch (IOException e) {
linkSpeed3G = "Failure";
e.printStackTrace();
} finally {
}
return linkSpeed3G;
}
/**
* Update list ui after process finished.
*/
protected void onPostExecute(String file_url) {
if (null != networkSped) {
networkSped.setText(linkSpeed3G);
if (linkSpeed3G.equalsIgnoreCase("Failure")) {
networkSped.setTextColor(0xE43F3F);
} else {
networkSped.setTextColor(0xff669900);
}
}
Toast.makeText(context, "linkSpeed3G " + linkSpeed3G, 3000).show();
}
public static String internetSpeed(long nSecs, long bytes, boolean showBits) {
if (nSecs != 0) {
BigDecimal secondsBigDecimal = BigDecimal.valueOf(nSecs).divide(BigDecimal.valueOf(1000000000), 2,
RoundingMode.HALF_UP);
// long secs = nSecs / 1000000000;
if (showBits) {
BigDecimal bitsBigDecimal = BigDecimal.valueOf(bytes * 8);
// long bits = bytes * 8;
if (secondsBigDecimal.signum() == 1) {
// float speed = bits / secs;
BigDecimal speeedBigDecimal = bitsBigDecimal.divide(secondsBigDecimal, 2, RoundingMode.HALF_UP);
long Kbit = 1024;
long Mbit = Kbit * 1024;
long Gbit = Mbit * 1024;
float speed = speeedBigDecimal.floatValue();
if (speed < Kbit)
return String.valueOf(speed) + " bit/Sc";
if (speed > Kbit && speed < Mbit)
return String.valueOf(speed / Kbit) + " Kb/S";
if (speed > Mbit && speed < Gbit)
return String.valueOf(speed / Mbit) + " Mb/S";
if (speed > Gbit)
return String.valueOf(speed / Gbit) + " Gb/S";
}
return "???";
} else {
BigDecimal bitsBigDecimal = BigDecimal.valueOf(bytes);
// long bits = bytes * 8;
if (secondsBigDecimal.signum() == 1) {
// float speed = bits / secs;
BigDecimal speeedBigDecimal = bitsBigDecimal.divide(secondsBigDecimal, 2, RoundingMode.HALF_UP);
long Kbit = 1024;
long Mbit = Kbit * 1024;
long Gbit = Mbit * 1024;
float speed = speeedBigDecimal.floatValue();
if (speed < Kbit)
return String.valueOf(speed) + " Byte/Sc";
if (speed > Kbit && speed < Mbit)
return String.valueOf(speed / Kbit) + " KB/S";
if (speed > Mbit && speed < Gbit)
return String.valueOf(speed / Mbit) + " MB/S";
if (speed > Gbit)
return String.valueOf(speed / Gbit) + " GB/S";
}
return "???";
}
}
return "###";
}
}
你是通过代理连接到互联网的吗?你能把e.printStackTrace()放进去吗;在接球区?然后把你收到的信息贴在这里??你是在Marshamallow上开发的吗?然后你需要请求运行时许可如果它不起作用,最简单的方法就是登录。错误。这里必须抛出一个异常,那么stacktrace是什么?@SouravKanta no不是proxy我如何设置超时??
new NetworkSpeedCheckTask(null, getApplicationContext()).execute();