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 在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) 在android.os.AsyncTask $ 2.call(AsyncTask.java:295) 在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) at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:588) 在java.lang.Thread.run(Thread.java:818)
答案 0 :(得分:0)
使用代理并检查每种情况下发送的内容。您可能会发现一些额外的标头可能会导致问题,具体取决于后端如何处理它们。