首页 > 解决方案 > 相同的代码在 java 中有效,但在 android 中无效

问题描述

try {
     //link below might contain offensive advertisemensts
     url = new URL("http://wasabisyrup.com/archives/GWB5lyn4FM8");
     urlConnection = (HttpURLConnection) url.openConnection();
     int c = urlConnection.getResponseCode();
.
.
.

此代码块在 java ide 上编译时会给出响应代码 200,但在使用 asynctask 在 android 上运行时会引发 403 错误。这真让我抓狂。请帮忙

安卓代码示例:

public class MainActivity extends Activity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Code here executes on main thread after user presses button
            new DownloadFilesTask().execute();
        }
    });


}

private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {

        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);
        URL url;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL("http://wasabisyrup.com/archives/GWB5lyn4FM8");
            urlConnection = (HttpURLConnection) url.openConnection();
            int c = urlConnection.getResponseCode();
            System.out.println(c);
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());

        }catch(Exception e){
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }
        return null;
    }

    protected void onProgressUpdate(Integer... progress) {
        //setProgressPercent(progress[0]);
    }

    protected void onPostExecute() {

    }
}

我得到的输出:

I/System.out:403 W/System.err:java.io.FileNotFoundException:http ://wasabisyrup.com/archives/GWB5lyn4FM8 在 com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238) W/System.err: 在 ml.melun.junhea.web_test.MainActivity$DownloadFilesTask.doInBackground(MainActivity.java:47) 在 ml .melun.junhea.web_test.MainActivity$DownloadFilesTask.doInBackground(MainActivity.java:35) at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java: 237) 在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 在 java.util.concurrent.ThreadPoolExecutor$Worker.run( ThreadPoolExecutor.java:588) 在 java.lang.Thread.run(Thread.java:818)

标签: javaandroid

解决方案


使用代理并检查您在每种情况下发送的内容。您可能会发现一些额外的标头可能会导致问题,具体取决于后端如何处理它们。


推荐阅读