将android手机直接连接到esp8266

时间:2016-04-12 08:37:56

标签: android-studio httpurlconnection androidhttpclient

我正在编写一个可以通过esp8266将数据发送到arduino板的Android应用程序。我一直在关注附加的代码,但我不知道如何将HttpClient更改为HttpURLConnection

/**
 * Description: Send an HTTP Get request to a specified ip address and port.
 * Also send a parameter "parameterName" with the value of "parameterValue".
 * @param parameterValue the pin number to toggle
 * @param ipAddress the ip address to send the request to
 * @param portNumber the port number of the ip address
 * @param parameterName
 * @return The ip address' reply text, or an ERROR message is it fails to receive one
 */
public String sendRequest(String parameterValue, String ipAddress, String portNumber, String parameterName) {
    String serverResponse = "ERROR";

    try {

        HttpClient httpclient = new DefaultHttpClient(); // create an HTTP client
        // define the URL e.g. http://myIpaddress:myport/?pin=13 (to toggle pin 13 for example)
        URI website = new URI("http://"+ipAddress+":"+portNumber+"/?"+parameterName+"="+parameterValue);
        HttpGet getRequest = new HttpGet(); // create an HTTP GET object
        getRequest.setURI(website); // set the URL of the GET request
        HttpResponse response = httpclient.execute(getRequest); // execute the request
        // get the ip address server's reply
        InputStream content = null;
        content = response.getEntity().getContent();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                content
        ));
        serverResponse = in.readLine();
        // Close the connection
        content.close();
    } catch (ClientProtocolException e) {
        // HTTP error
        serverResponse = e.getMessage();
        e.printStackTrace();
    } catch (IOException e) {
        // IO error
        serverResponse = e.getMessage();
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // URL syntax error
        serverResponse = e.getMessage();
        e.printStackTrace();
    }
    // return the server's reply/response text
    return serverResponse;
}

0 个答案:

没有答案