android httpsurlconnection onclick

时间:2017-04-04 09:34:19

标签: java android httpsurlconnection

我开始冒险使用android并尝试make app,它会在登录后从网站下载数据。我已经编写了以这种方式连接网站的方法:

public class ConnectWebsite extends AsyncTask<String, Void, String> {
String server_response;
public static final int CONNECTON_TIMEOUT_MILLISECONDS = 60000;

@Override
protected String doInBackground(String... strings) {
    String result = "";
    InputStream is = null;
    URL url;
    HttpsURLConnection urlConnection = null;
    try {
        url = new URL(strings[0]);
        urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(CONNECTON_TIMEOUT_MILLISECONDS);
        urlConnection.setReadTimeout(CONNECTON_TIMEOUT_MILLISECONDS);
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoInput(true);
        urlConnection.connect();
        int responseCode = urlConnection.getResponseCode();
        if(responseCode != HttpsURLConnection.HTTP_OK) {
            throw new IOException("HTTP error code: " + responseCode);
        }
        is = urlConnection.getInputStream();
        if (is != null) {
            // Converts Stream to String with max length of 500.
            result = readStream(is, 500);
        }


    } catch (MalformedURLException e) {
        Log.d("ConnectWebsite ", Log.getStackTraceString(e));
        e.printStackTrace();
    } catch (IOException e){
        Log.d("ConnectWebsite ", Log.getStackTraceString(e));
        e.printStackTrace();
    }
    return result;
}
private String readStream(InputStream stream, int maxLength) throws IOException {
 ...
}

不幸的是,当调试器将来到urlConnection.connect()时,应用程序抛出异常“无法执行android的方法:onClick”

编辑: 服务onclick的功能

  public void login(View w){
    Toast.makeText(this, "Login...", Toast.LENGTH_LONG).show();
    ConnectWebsite conn = new ConnectWebsite();
    String url = "http://examplewebsite.com";
    conn.execute(url);
}

编辑V2:

它几乎运作良好,我必须在清单中声明使用权限:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="myProject">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

0 个答案:

没有答案