gpt4 book ai didi

java - 相同的代码在java中有效,但在android中无效

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:38 25 4
gpt4 key购买 nike

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 错误。这真让我抓狂。请帮忙

Android 代码示例:

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 at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238) W/System.err: at ml.melun.junhea.web_test.MainActivity$DownloadFilesTask.doInBackground(MainActivity.java:47) at 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) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818)

最佳答案

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

关于java - 相同的代码在java中有效,但在android中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50686314/

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