java - 相同的代码在 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)
解决方案
使用代理并检查您在每种情况下发送的内容。您可能会发现一些额外的标头可能会导致问题,具体取决于后端如何处理它们。
推荐阅读
- c++ - C++Builder 无法正确编译(无法识别某些函数)
- python - 加入数据框会引发警告
- android - 本机android未连接到socket.io
- java - 如何转换 SearchHits
返回页面类型 spring data elasticsearch 4.0中的返回类型 - php - 在 AES-GCM-256 PHP 中加密长度超过 256 的字符串
- python - 使用 pandas 如何迭代 2 个备用向量行,使用 scipy 计算并保存到新列
- mysql - MySQL 中窗口函数的约束和限制
- python - 如何使用多个单词的两个参数
- javascript - 在 Illustrator JavaScript 中导入模块?
- node.js - 用户保存令牌的 Mongoose TTL