我(有时)在发出 HTTPRequest 时遇到 EOFException。我已经尝试设置 keepalive ="false" 但这没有帮助,所以我想问题一定出在其他地方......(我已经获得了 INTERNET 权限)......这个 AsyncTask 有时可能正在运行可能是一个问题同时不止一次?)我使用的代码是
package jo.z.invg.fahrplan;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Scanner;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.cookie.SetCookie;
import org.apache.http.impl.cookie.BasicExpiresHandler;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
class PostRequest extends AsyncTask<PostParam, Void, String> {
//private Exception exception;
class LenientCookieSpec extends BrowserCompatSpec {
public LenientCookieSpec() {
super();
registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(DATE_PATTERNS) {
@Override public void parse(SetCookie cookie, String value) throws MalformedCookieException {
if (TextUtils.isEmpty(value)) {
// You should set whatever you want in cookie
cookie.setExpiryDate(null);
} else {
super.parse(cookie, value);
}
}
});
}
}
private boolean succ = true;
private int info;
private int reqnr;
private ScheduleRequest sreq;
@Override
protected String doInBackground(PostParam...postData) {
//build the string to store the response text from the server
Log.d("Test", "Anfrage gesendet");
String response= "***";
reqnr = postData[0].reqnr;
sreq = postData[0].req;
info = postData[0].in;
System.setProperty("http.keepAlive", "false");
//do this wherever you are wanting to POST
URL url;
HttpURLConnection conn;
try{
//if you are using https, make sure to import java.net.HttpsURLConnection
url=new URL(postData[0].adress);
//you need to encode ONLY the values of the parameters
String param = EncodeParam(postData[0].postparam);
conn=(HttpURLConnection)url.openConnection();
//set the output to true, indicating you are outputting(uploading) POST data
conn.setDoOutput(true);
//once you set the output to true, you don't really need to set the request method to post, but I'm doing it anyway
conn.setRequestMethod("POST");
conn.setInstanceFollowRedirects(true);
//Android documentation suggested that you set the length of the data you are sending to the server, BUT
// do NOT specify this length in the header by using conn.setRequestProperty("Content-Length", length);
//use this instead.
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:15.0) Gecko/20120830 Firefox/15.0");//User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:15.0) Gecko/20120830 Firefox/15.0
//send the POST out
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.close();
//start listening to the stream
Scanner inStream = new Scanner(conn.getInputStream());
//process the stream and store it in StringBuilder
while(inStream.hasNextLine()){
response+=(inStream.nextLine());}
//Log.d("HTTPRequest",response);
conn.disconnect();
}
//catch some error
catch(MalformedURLException ex){
//Toast.makeText(MyActivity.this, ex.toString(), 1 ).show();
Log.d("HTTPRequest", "Problem beim Postrequest",ex);
}
// and some more
catch(IOException ex){
succ = false;
if(!(INVG_Fahrplan.INVG_this.isOnline())){INVG_Fahrplan.INVG_this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(INVG_Fahrplan.INVG_this,"Keine Internetverbindung", Toast.LENGTH_LONG).show();
}
});}
else{
INVG_Fahrplan.INVG_this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(INVG_Fahrplan.INVG_this,"Fehler bei der Abfrage", Toast.LENGTH_LONG).show();
}
});
}
Log.d("HTTPRequest", "Problem beim Postrequest",ex);
//Toast.makeText(MyActivity.this, ex.toString(), 1 ).show();
}
return response;
}
public String EncodeParam (List<PostNameValuePair> para){
String param = "";
for (PostNameValuePair nvp: para){
try{
param += nvp.name +"=" + URLEncoder.encode(nvp.value, "UTF-8") + "&";
}catch (Exception e){
Log.d("HTTPRequest", "Problem beim Postrequest",e);
}
}
return param.substring(0, param.length()-1);
}
protected void onPostExecute(String result) {
if(succ){
if (info == 1){
sreq.ParseRequest(result,1,-1,reqnr);
}else if (info == 2){
sreq.ParseDetails(result,reqnr);
}}else{
sreq.reqerror(info);
}
//sreq.ParseRequest(result,1);
}
}
提前感谢您的帮助;D