gpt4 book ai didi

java - HttpURLConnection 不适用于 Android

转载 作者:行者123 更新时间:2023-12-02 02:49:51 24 4
gpt4 key购买 nike

我有一个问题,真的不知道出了什么问题:-/

我有一个简单的函数,在单击按钮后调用

public void clickFunc(View view) {

StringBuilder result = new StringBuilder();
try {
URL url = new URL("http://google.com");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
int responseCode=conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {

InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String line;

while ((line = reader.readLine()) != null) {

result.append(line);
}
in.close();
httpTxt.setText(result.toString());

}
else {
httpTxt.setText("false : "+responseCode);
}
}
catch(Exception e){
httpTxt.setText("Exception: " + e.getMessage());
}


}

但是单击后我的输出是 Exception: null

在 list 中我有<uses-permission android:name="android.permission.INTERNET" />

我认为此代码与此处或互联网上提到的所有代码相同:-/

httptxt 是我的页面输出的 texview

谢谢

最佳答案

好吧,我不知道我必须在后台执行此操作...它现在正在工作,谢谢!

public void clickFunc(View view) {

new SendPostRequest().execute();
}
private class SendPostRequest extends AsyncTask<Void, Void, String> {

protected String doInBackground (Void... params) {

StringBuilder result = new StringBuilder();
HttpURLConnection conn = null;
BufferedReader reader;

try {
URL url = new URL("http://stackoverflow.com");

conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
int responseCode=conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {

InputStream in = new BufferedInputStream(conn.getInputStream());
reader = new BufferedReader(new InputStreamReader(in));

String line;

while ((line = reader.readLine()) != null) {

result.append(line);
}
in.close();
return(result.toString());

}
else {
return("false : "+responseCode);
}
}
catch(Exception e){
return("Exception: " + e.getMessage());
}
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
httpTxt.setText(s);
}

}

我不是一个 Android 程序员,所以即使它是基本的我也不知道,对不起大家:)

关于我的应用程序,如果您感兴趣,为什么我想要它 - 我读取条形码,转到 php 脚本,查看数据库是否有此代码并返回 true 或 false

关于java - HttpURLConnection 不适用于 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44022280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com