当前位置: 代码迷 >> java >> HttpUrlConnection使用一个网址,但不能使用另一个网址
  详细解决方案

HttpUrlConnection使用一个网址,但不能使用另一个网址

热度:65   发布时间:2023-07-26 14:25:12.0

一个网址与asynctask中的HttpUrlConnection一起很好地工作,但是另一个仍在发布并请求相同数据的URL使应用程序崩溃。

但是同一服务器目录中有其他文件,并且它们的DoInput和DoOutput成功

@Override
protected String doInBackground(String... params)
{
    try {

        getter_url = new URL("this one returns successfully");
        getter_url0 = new URL("this one just crashes the app");

    } catch (MalformedURLException e) {
        Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
        // TODO Auto-generated catch block
        e.printStackTrace();
        return e.toString();
    }
    afbah= params[0];
    if (afbah.equals("whfiavbkjnfdl"))
    {
        String kbfisy= params[1];
        try
        {
            try {
                httpURLConnection = (HttpURLConnection) getter_url0.openConnection();
            }catch (Exception e){
                Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
                return e.toString();
            }
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String data = URLEncoder.encode("gisyfgb", "UTF-8") + "=" + URLEncoder.encode(kbfisy, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            StringBuilder ANSWER = new StringBuilder();
            String response = "";
            String line = "";
            while ((line = bufferedReader.readLine()) != null)
            {
                ANSWER.append(line).append("\n");
                response+= line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return response;

我真的不明白为什么两个网址的行为会有所不同

在邮递员API上,这两个URL成功,但是第一个URL的HttpUrlConnection成功,第二个URL的错误。

请问我需要帮助的任何信息

示例网址是什么? URL可能无法正确解析,请尝试以下方法:

URL url = new URL(urlString);
URI uri = new URI(
    url.getProtocol(),
    url.getUserInfo(),
    url.getHost(),
    url.getPort(),
    url.getPath(),
    url.getQuery(),
    url.getRef()
);

HttpURLConnection connection = (HttpURLConnection) new URL(uri.toASCIIString()).openConnection();
  相关解决方案