gpt4 book ai didi

java - HttpURLconnection 与非 .com 网站的连接失败

转载 作者:行者123 更新时间:2023-12-02 04:54:28 25 4
gpt4 key购买 nike

我一直在尝试将我的 Android 应用程序连接到 php 服务器。我创建了一个 php 服务器 echo “连接成功” 以便我可以检索相同的文本并显示它位于我的 Android 应用程序的 Alertbox 中。我有一个带有 .cf 的网站,每次连接时该应用程序都会关闭。我检查了我的代码,没有发现任何问题,然后我尝试了 .com 网站,该应用程序成功地能够检索页面上显示的任何内容的 html 形式。那么是否有什么东西可以阻止 HttpURLconnection 形式连接到非 .com 网站。

这是代码。

public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}//takes context as an argument
@Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://www.thejoint.cf/test.php";
if(type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);//what does the url object have
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

@Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
Log.i("info",result);
alertDialog.show();
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}

}

最佳答案

So is there something that prevents HttpURLconnection form connecting to non .com websites ?

您创建一个正则表达式:

String expression  =  "[^"]+\.com" ; 

并测试您的网址是否与其匹配:

if(your_url.matches(expression)){

// your url end with .com , do what you want

}else{

// your url doesn't end with .com , do what you want

}

关于java - HttpURLconnection 与非 .com 网站的连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56417532/

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