Android Studio 亲感受之无法访问URL

来源:互联网 发布:linux locate which 编辑:程序博客网 时间:2024/05/01 11:05

访问URL的方法代码如下:

package SuComs.http;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnection;public class corequest {    public static SuComs.result.coresult Get(String _url)    {        return Get(_url, new SuComs.para.coparas());    }    public static SuComs.result.coresult Get(String _url, SuComs.para.coparas _paras)    {        SuComs.result.coresult __temp = new SuComs.result.coresult();        String __paras = "paras=" + _paras.UrlEncode();        PrintWriter out = null;        BufferedReader in = null;        try {            URL realUrl = new URL(_url);            //打开和URL之间的连接              URLConnection conn = realUrl.openConnection();            //设置通用的请求属性              conn.setRequestProperty("accept", "*/*");            conn.setRequestProperty("connection", "Keep-Alive");            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");            //发送POST请求必须设置如下两行              conn.setDoOutput(true);            conn.setDoInput(true);            //获取URLConnection对象对应的输出流              out = new PrintWriter(conn.getOutputStream());            //发送请求参数              out.print(__paras);            //flush输出流的缓冲              out.flush();            //定义BufferedReader输入流来读取URL的响应              in = new BufferedReader(                    new InputStreamReader(conn.getInputStream()));            String line;            String str = "";            while ((line = in .readLine()) != null) {                str += line;            }            __temp = new SuComs.result.coresult();            __temp.Data(str);        } catch (Exception e) {            __temp.Success(false);            __temp.Error("发送POST请求出现异常!" + e);            e.printStackTrace();        }        //使用finally块来关闭输出流、输入流          finally {            try {                if (out != null) {                    out.close();                }                if ( in != null) { in .close();                }            } catch (IOException ex) {                ex.printStackTrace();            }        }        return __temp;    }}

在Android Studio调试时,发现在 out = new PrintWriter(conn.getOutputStream());处报错,错误提示java.io.eofexception

后查找资料,该方法需要放在线程中执行,在这里搁到了Task中执行

0 0
原创粉丝点击