0
我有多個應用程序使用相同的代碼將HttpsURLConnection連接到服務器。有時候,我無法與設備進行任何通信,但運行相同HttpsURLConnection代碼的不同設備到相同的服務器地址沒有任何問題。Android Studio間歇性HttpsURLConnection失敗
有時第一個設備會在多次嘗試似乎自行完成後進行連接。但是重置設備上的wifi連接總是會立即修復它。
這使我相信連接到服務器的路由器將設備從它的路由表中刪除,但是我會很感激代碼上的一雙額外的眼睛。
我有一個單獨的活動,以與下面的代碼HttpsURLConnection的:
class WebRequest {
static String response = null;
public final static int GET = 1;
private final static int POST = 2;
//Constructor with no parameter
public WebRequest() {
}
/**
* Making web service call
*
* @url - url to make request
* @requestmethod - http request method
*/
public String makeWebServiceCall(String url, int requestmethod) {
return this.makeWebServiceCall(url, requestmethod, null);
}
/**
* Making service call
*
* @url - url to make request
* @requestmethod - http request method
* @params - http request params
*/
private String makeWebServiceCall(String urladdress, int requestmethod,
HashMap<String, String> params) {
URL url;
String response = "";
try {
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
if (requestmethod == POST) {
conn.setRequestMethod("POST");
} else if (requestmethod == GET) {
conn.setRequestMethod("GET");
}
if (params != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
我打電話了的AsyncTask內使用從另一個活動代碼:
WebRequest webreq = new WebRequest();
request = webreq.makeWebServiceCall(URL, WebRequest.GET);
我很擔心,代碼中的某些內容導致該設備中的間歇性連接問題。我注意到的一件事是沒有connection.disconnect。
謝謝你對這個問題的任何見解!
它與你的代碼無關。但是你用這個設備解釋。 – greenapps
感謝您的關注。我忘記添加的一件事是停止使HttpUrlConnections能夠通過其他應用程序,YouTube,Google est連接到互聯網的設備,但互聯網和服務器都在同一個路由器上。 – matthew