java - android http 请求的未知主机异常应返回 XML

标签 java android xml web-services http

我使用以下类发送 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);





}


}

最佳答案

确保您已在 AnroidManifest 文件中声明 INTERNET 权限,并且具有互联网连接。

您应该在 AndroidManifest 中声明此权限:

<uses-permission android:name="android.permission.INTERNET" />

关于java - android http 请求的未知主机异常应返回 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12294510/

相关文章:

java - BlobstoreService 的 HttpSession Null

java - 如果更新的客户端请求中不存在保存的对象,是否可以删除数据库条目?

Android 分享 Intent 选择器

android - HTML 电子邮件未在 Android 电子邮件上显示完整宽度

java - 是时候读取 xml 文件了

Android 颜色资源 - 使一种颜色成为另一种颜色的别名

java - 如何存储一个大(10位)整数?

android - 以编程方式为单词预测添加单词

机器人 : How to change background layout when focus and active

java - 我如何压缩或编码椭圆曲线公钥并将其放在网络上?