0

次のクラスを使用してhttpリクエストを送信し、Androidプロジェクトで返されるXML応答を取得します。ただし、UnknownHostExceptionは、要求を送信しようとするとスローされます。この問題について私を助けてください。

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;    
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

import android.os.AsyncTask;
import android.util.Xml;

class RequestTask extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();                
            responseString = out.toString();
        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        //TODO Handle problems..
    } catch (IOException e) {
        String s=e.toString();
        System.out.println(s);
        //TODO Handle problems..
    }
    return responseString;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    //Do anything with response..
    System.out.println(result);





}


}
4

1 に答える 1

1

AnroidManifestファイルでインターネットアクセス許可を宣言し、インターネットに接続していることを確認してください。

この権限をで宣言する必要がありますAndroidManifest:

<uses-permission android:name="android.permission.INTERNET" />
于 2012-09-06T06:57:41.867 に答える