SocketException( Connection timed out ) is thrown when i run my android app on a real device

一世执手 提交于 2019-12-12 01:49:00

问题


My android app needs to perform Http requests through HttpClient.
i've tested on the emulator and it works fine. but when i do it on a real device with WIFI activated, sometimes ANR occurred, and sometimes SocketException is thrown.
it seems that the device is not able to connect the server.
logcat print-out is as follows

in addition, the package name for the app is "com.tim.wirelessorder"

06-03 09:51:17.803: W/System.err(2307): java.net.SocketException: The operation timed out
06-03 09:51:17.803: W/System.err(2307):     at org.apache.harmony.luni.platform.OSNetworkSystem.connectStreamWithTimeoutSocketImpl(Native Method)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.harmony.luni.platform.OSNetworkSystem.connect(OSNetworkSystem.java:115)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:244)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:533)
06-03 09:51:17.803: W/System.err(2307):     at java.net.Socket.connect(Socket.java:1055)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-03 09:51:17.803: W/System.err(2307):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-03 09:51:17.803: W/System.err(2307):     at com.tim.wirelessorder.util.net.HttpUtil.getHttpResponse(HttpUtil.java:43)
06-03 09:51:17.803: W/System.err(2307):     at com.tim.wirelessorder.ui.SignIn$BnListener.onClick(SignIn.java:117)
06-03 09:51:17.803: W/System.err(2307):     at android.view.View.performClick(View.java:2408)
06-03 09:51:17.803: W/System.err(2307):     at android.view.View$PerformClick.run(View.java:8818)
06-03 09:51:17.803: W/System.err(2307):     at android.os.Handler.handleCallback(Handler.java:587)
06-03 09:51:17.803: W/System.err(2307):     at android.os.Handler.dispatchMessage(Handler.java:92)
06-03 09:51:17.803: W/System.err(2307):     at android.os.Looper.loop(Looper.java:123)
06-03 09:51:17.810: W/System.err(2307):     at android.app.ActivityThread.main(ActivityThread.java:4627)
06-03 09:51:17.810: W/System.err(2307):     at java.lang.reflect.Method.invokeNative(Native Method)
06-03 09:51:17.810: W/System.err(2307):     at java.lang.reflect.Method.invoke(Method.java:521)
06-03 09:51:17.810: W/System.err(2307):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-03 09:51:17.810: W/System.err(2307):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-03 09:51:17.810: W/System.err(2307):     at dalvik.system.NativeStart.main(Native Method)
06-03 09:51:28.289: W/KeyCharacterMap(2307): Can't open keycharmap file
06-03 09:51:28.289: W/KeyCharacterMap(2307): Error loading keycharmap file '/system/usr/keychars/ilitek_ts.kcm.bin'. hw.keyboards.65538.devname='ilitek_ts'
06-03 09:51:28.289: W/KeyCharacterMap(2307): Using default keymap: /system/usr/keychars/qwerty.kcm.bin

this problem is really disturbing, because i'm not developing an app which only can be run on an emulator. that won't make any sense. can anybaby figure out what problem is?

my code is here.

                    HttpPost request = HttpUtil.getHttpPost(url);
                    List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
                    BasicNameValuePair vName = new BasicNameValuePair(
                            "name", name);
                    list.add(vName);
                    BasicNameValuePair vPwd = new BasicNameValuePair("pwd",
                            pwd);
                    list.add(vPwd);
                    // Log.e("result", "kk:");
                    request.setEntity(new UrlEncodedFormEntity(list));
                    HttpResponse response = HttpUtil
                            .getHttpResponse(request);
// -------- the line above throws the SocketException. this is a static method. the code is added below.

======

public static HttpGet getHttpGet(String url) {
    Log.e("url", url);
    HttpGet request = new HttpGet(url);
    return request;
}


public static HttpPost getHttpPost(String url) {
    HttpPost request = new HttpPost(url);
    return request;
}
public static HttpResponse getHttpResponse(HttpGet request)
        throws ClientProtocolException, IOException {
    // Log.e("http", "in ");
    HttpResponse response = new DefaultHttpClient().execute(request);
    // Log.e("http", (response == null) + " ");
    return response;
}


public static HttpResponse getHttpResponse(HttpPost request)
        throws ClientProtocolException, IOException {
    HttpResponse response = new DefaultHttpClient().execute(request);
// ------- and here it performs a HttpPost request, and it seems the request fails to be sent.
        return response;
    }

this is the do-post code on the server. the servlet receives the request, and get the name, pwd parameter from the client entered by users on UI. then servlet activates a DAO which uses the name, pwd to do queries in MySQL. you can see a "System.out.println(name)" line by which i want to make sure whether the servlet obtains the request. and when i test the code on a real device, the console doesn't give any print-out. and i think this means the servlet doesn't receive the request.

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    OutputStream out = response.getOutputStream();
    String name = request.getParameter("name");
    String pwd = request.getParameter("pwd");
    System.out.println(name);

    UserDao dao = new UserDaoImpl();

    byte[] r = dao.query(name, pwd);
    out.write(r);
    out.close();
}

回答1:


Try using another method of sending HTTP request:

url = "http://<your URL>";
URL urlObj = new URL(url);
Log.d("DEBUG", "url=" + url);
URLConnection lu = urlObj.openConnection();

//optional - send parameters
String data = URLEncoder.encode("param", "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); //optional - send parameters
// Send data
lu.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(lu.getOutputStream());
wr.write(data);
wr.flush();
//end of "optional"

// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(lu.getInputStream()));
String line = "", res = "";
while ((line = rd.readLine()) != null) {
    res += line;
}

wr.flush();
wr.close();
Log.d("DEBUG", "res=" + res);



回答2:


When ever I get this its when I get no data connection. Also check you have the right permissions cause that can do it to.



来源:https://stackoverflow.com/questions/10867434/socketexception-connection-timed-out-is-thrown-when-i-run-my-android-app-on-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!