最近出现很诡异的情况,可能是我对内部细节不了解。在android模拟器上访问外网获取数据成功,但把程序放到手机上,怎么也不行,我用java自带的net包写的。
运行到httpConn.getResponseCode()就异常,没有返回请求码。异常信息是:java.net.SocketException:Connetion reset by peer。哪位帮忙解答一下。谢谢啦。

解决方案 »

  1.   


    /**
     * 使用get请求以普通方式java.net请求数据
     * 
     * @param path
     * @return
     */
    public static String doGetByOrdinary(String path) {
    HttpURLConnection httpConn = null;
    BufferedReader reader = null;
    try {
    URL url = new URL(path);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setRequestMethod("GET");
    httpConn.setConnectTimeout(5000);
    httpConn.setReadTimeout(5000);
    if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    StringBuilder builder = new StringBuilder();
    reader = new BufferedReader(new InputStreamReader(httpConn
    .getInputStream(), "UTF-8"));
    for (String s = reader.readLine(); s != null; s = reader
    .readLine()) {
    builder.append(s);
    }
    return builder.toString();
    }
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (reader != null)
    reader.close();
    if (httpConn != null)
    httpConn.disconnect();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    return null;
    }代码就是这样滴,在J2EE上运行正常,在手机上运行失败,是不是需要配置服务器的参数
      

  2.   

    /**
     * 使用get请求以HttpClient org.apache.http请求数据
     * 
     * @param path
     * @return
     * @throws IOException 
     * @throws ClientProtocolException 
     * @throws IOException
     */
    public static String doGetByHttpClient(String path) throws ClientProtocolException, IOException {
    HttpClient hc = new DefaultHttpClient(getHttpParams());
    HttpGet request = new HttpGet(path);
    System.out.println("1:============================");
    // request.addHeader("Content-Type", "application/json; charset=utf-8");
    HttpResponse response = hc.execute(request);
    System.out.println("2:============================");
    // System.out.println(response.getStatusLine().getStatusCode());
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
    // return EntityUtils.toString(response.getEntity());
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent(), "UTF-8"));
    for (String s = reader.readLine(); s != null; s = reader.readLine()) {
    builder.append(s);
    }
    if (reader != null)
    reader.close();
    return builder.toString();
    }
    return null;
    }
    在运行到HttpResponse response = hc.execute(request);
    时就会报错。java.net.SocketException:Connetion reset by peer。求解答
      

  3.   

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.INTERNET" />
    在AndroidManifest.xml 中。 
    没加的话。可以执行。但是会抛异常