我正在构建一个与nodemcu连接的应用。在我的代码中,我使用的是HttpClient
,但正如我所读到的那样,它已不再受支持了。我想在下面的代码中使用httpurlConnection
。如果使用httpurlconnection
,我会收到错误。这是代码
if (!dialog.isShowing())
dialog.show();
String val = params[0];
final String url = "http://" + serverAdress + "/led/" + val;
try {
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet();
getRequest.setURI(new URI(url));
HttpResponse response = client.execute(getRequest);
InputStream inputStream = null;
inputStream = response.getEntity().getContent();
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inputStream));
serverResponse = bufferedReader.readLine();
inputStream.close();
} catch (URISyntaxException e) {
e.printStackTrace();
serverResponse = e.getMessage();
} catch (ClientProtocolException e) {
e.printStackTrace();
serverResponse = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
serverResponse = e.getMessage();
}
return serverResponse;
}
答案 0 :(得分:1)
我建议你看一下OkHttp图书馆。实际上,最新版本的HttpsURLConnection使用OkHttp引擎盖。或更高级别的库Retrofit,它使用OkHttp但其API更易于使用。此外,如果您的服务器是RESTful,您可以使用适配器/转换器简单地反序列化对Java对象的响应。
答案 1 :(得分:0)
试试这个:
HttpsURLConnection request = (HttpsURLConnection) (url.openConnection());
request.setRequestMethod("GET");
request.connect();
String result = readStream(request.getInputStream());
request.disconnect();