HttpUrlConnection使用一个url而不是另一个url

问题描述 投票:0回答:1

一个URL适用于asynctask中的HttpUrlConnection,但另一个仍然发布并请求相同的数据会使应用程序崩溃。

但是同一个服务器目录有其他文件,并且它们的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;

我真的无法理解为什么两个URL的行为会有所不同

在postman API上,它会使两个URL成功,但HttpUrlConnection会导致第一个URL成功,而第二个URL会出错。

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

java android httpurlconnection
1个回答
0
投票

什么是示例网址?可能无法正确解析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();
© www.soinside.com 2019 - 2024. All rights reserved.