【已解决】 使用Java的api进行请求数据 出现SocketTimeoutException异常
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadJson(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url=new URL("http://10.0.2.2:9102/get/text");
HttpURLConnection Connection = (HttpURLConnection) url.openConnection();
Connection.setConnectTimeout(10000);
Connection.setRequestMethod("GET");
Connection.setRequestProperty("Accept-Language","zh-CN,zh;q=0.9");
Connection.setRequestProperty("Accept-Encoding","gzip, deflate");
Connection.setRequestProperty("Accept","*/*");
Connection.connect();
//结果码
int responseCode = Connection.getResponseCode();
if (responseCode==200) {
Map<String, List<String>> headerFields = Connection.getHeaderFields();
Set<Map.Entry<String, List<String>>> entries = headerFields.entrySet();
for (Map.Entry<String, List<String>> entry : entries) {
Log.d(TAG, entry.getKey()+"---------->"+entry.getValue());
}
Object content = Connection.getContent();
Log.d(TAG, "content--->"+content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
以下是异常,PS:我用的是Android studio的原生模拟器

你服务器程序运行起来了吗?
另外,你可以先用手机的浏览器请求一下,看看能不能访问嘛。这样子再确定一下自己写的代码是否有问题,还是服务器访问的问题。