Android中的HttpUrlConnection没有错误但无法正常工作

时间:2016-05-19 06:46:37

标签: android http httpclient httpurlconnection

我不熟悉Android Studio上的HttpUrlConnection。我尝试在Eclipse中使用HttpClient进行编码,它可以工作。 HttpClient现在已在Android Studio中弃用,因此我尝试使用HttpUrlConnection进行更改。我在Android Studio中的代码是这样的:

public String LedOff(View view) {
    try {
        URL url = new URL("http://192.168.4.1/LEDOff");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

Eclipse中的

是这样的:

public void LedOff (View view){

        String url = "http://192.168.4.1/LEDOff";

        HttpClient httpClient = new DefaultHttpClient();

        try {
            httpClient.execute(new HttpGet(url));
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

我不知道什么是错的。请帮帮我。感谢。

3 个答案:

答案 0 :(得分:2)

确保您的Manifest中有这两个权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

修改
添加了LedOff()方法的代码,将成功的响应视为String

按照Android Docs尝试此操作:

public String LedOff(View view) {
    try {
        URL url = new URL("http://192.168.4.1/LEDOff");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET"); // Or any method you need
        conn.setDoInput(true);

        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response code is: " + response);

        if ((response >= 200) && (response < 300)) {
            // We are assuming here that whatever the response is, it can be parsed as a String
            Log.d(DEBUG_TAG, "The response is: " + conn.getResponseMessage());
        }
    } catch(Exception ex) {
        // Handle any exceptions
    }
}

答案 1 :(得分:1)

您必须通过调用getInputStream()getResponseCode()getResponseMessage()来提交请求,以便返回和处理回复。

Connect()方法只是创建连接。

检查:

Log.i("Response Code" , urlConnection .getResponseCode()); 

看看你得到了什么回应。

答案 2 :(得分:0)

试试这个

var tsProject = ts.createProject(paths.typescriptRoot + 'tsConfig.json'); // use tsconfig.json
    gulp.task("tsbuild", function () {
        var tsResult = tsProject.src()
            .pipe(sourcemaps.init()) // needed to create sourcemaps
            .pipe(ts(tsProject)); // use tsconfig.json
        return tsResult.js
            .pipe(concat(paths.concatTsFileName)) // concat all output files into a sings js files
            .pipe(sourcemaps.write()) // write the sourcemap to be able to debug the ts files
            .pipe(gulp.dest(paths.typescriptOut)); // output the result on specific path
    });