gpt4 book ai didi

java - 如何在java中超时连接到服务器

转载 作者:行者123 更新时间:2023-11-29 08:59:46 25 4
gpt4 key购买 nike

private String getHttpResponse(String lName,String consultancyArea,String fName,String hospitalName,String date,String time){
String names="a";
System.out.println("iside httprespons");
HttpParams httpParams=new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
HttpConnectionParams.setSoTimeout(httpParams,30000);
HttpClient httpClient=new DefaultHttpClient(httpParams);
HttpPost httpPost=new HttpPost("url");

try{
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("LName", lName));
nameValuePairs.add(new BasicNameValuePair("ConsultancyArea", consultancyArea));
nameValuePairs.add(new BasicNameValuePair("fName", fName));
nameValuePairs.add(new BasicNameValuePair("hospitalName",hospitalName));
nameValuePairs.add(new BasicNameValuePair("date", date));
nameValuePairs.add(new BasicNameValuePair("time", time));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));



HttpResponse httpResponse=httpClient.execute(httpPost);
String result=inputStreamToString(httpResponse.getEntity().getContent()).toString();
JSONObject jasonObejct=new JSONObject(result);
String name1 = jasonObejct.getString("myData");

names=name1;


}catch (JSONException e) {
System.out.println("network error ocured1");
e.printStackTrace();

}catch(ConnectTimeoutException e){
System.out.println("network error ocured2");
}
catch(java.net.SocketTimeoutException e){
System.out.println("network error ocured2");
e.printStackTrace();
}
catch (ClientProtocolException e) {
System.out.println("network error ocured2");
e.printStackTrace();
System.out.println("network error ocured");
}
catch (IOException e) {

System.out.println("network error ocured3");
e.printStackTrace();
}
return names;
}

我正在开发一个安卓应用程序来从远程服务器获取数据。如果服务器没有响应,我想在 Activity 管理器卡住 Activity 之前使连接超时并结束进程。我需要的是一种在 android Activity 管理器卡住 Activity 之前结束进程的方法,以防服务器出现故障。

最佳答案

使用 AsyncTask,将您的代码粘贴到 doInBackground 方法中。 onPreExecute 和 onPostExecute 方法在 UI 线程上工作,但 doInBackground 创建单独的线程。

关于java - 如何在java中超时连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18214250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com