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

时间:2019-02-12 14:29:27

标签: java android httpurlconnection

一个URL与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;

我真的不明白为什么两个URL的行为会不同

在邮递员API上,这两个URL均成功完成,但第一个URL的HttpUrlConnection成功,而第二个URL则成功了。

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

1 个答案:

答案 0 :(得分: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();