无法通过Android连接到Web服务

时间:2012-01-27 13:00:29

标签: java android servlets ant jetty

我目前无法在Android上连接到我的网络服务。我正在使用Jetty Web服务并使用ANT构建它。在我的笔记本电脑上它完美运行并显示我的数据库中的项目但是它似乎无法在我的Android应用程序上连接。附件是代码和LOGCAT报告。

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class Android2Servlet extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dbtest);
TextView txtresp = (TextView)findViewById(R.id.servlet_response);

String url = "http://(MY LAPTOPS IP):8085/DB";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response); 
System.out.println(helpedResp); 
txtresp.setText(helpedResp);
System.out.println(response);
}catch(Exception ex){
txtresp.setText("Failed!");
ex.printStackTrace();
}
} }

HTTP解包文件

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
public class HttpUnpack {
public static String request(HttpResponse response){
String result = "";
try{ InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error retrieving response";
}
return result;
}
}

HTTP Unpack和Android2Servlet不会导致任何错误,但是文本框只返回“失败!”。

LOGCAT文件

W/System.err(1282): android.os.NetworkOnMainThreadException
W/System.err(1282):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
W/System.err(1282):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
W/System.err(1282):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
W/System.err(1282):     at libcore.io.IoBridge.connect(IoBridge.java:112)
W/System.err(1282):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
W/System.err(1282):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
W/System.err(1282):     at java.net.Socket.connect(Socket.java:842)
W/System.err(1282):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
W/System.err(1282):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
W/System.err(1282):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
W/System.err(1282):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
W/System.err(1282):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
W/System.err(1282):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err(1282):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
W/System.err(1282):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
W/System.err(1282):     at myFood.myFood.Android2Servlet.onCreate(Android2Servlet.java:24)
W/System.err(1282):     at android.app.Activity.performCreate(Activity.java:4465)
W/System.err(1282):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
W/System.err(1282):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
W/System.err(1282):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
W/System.err(1282):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
W/System.err(1282):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
W/System.err(1282):     at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(1282):     at android.os.Looper.loop(Looper.java:137)
W/System.err(1282):     at android.app.ActivityThread.main(ActivityThread.java:4424)
W/System.err(1282):     at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(1282):     at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err(1282):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
W/System.err(1282):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
W/System.err(1282):     at dalvik.system.NativeStart.main(Native Method)

任何回复都会非常有帮助。

问候。

编辑:

我现在已经删除了网络访问并将其放在另一个Java类中。并将其称为另一个类。它仍然返回相同的错误。还有其他建议吗?

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class androidconnectors {

    public static final String main(String args[]) throws Exception {


String txtresp = "";
try{
    String url = "http://(LAPTOPS IP):8085/Hello";
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response); // Http Unpack is not part of
System.out.println(helpedResp); // of HttpClient library
txtresp =(helpedResp);
System.out.println(response);
}catch(Exception ex){
    ex.printStackTrace();
}
return txtresp;
}
}

和android类。

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Settings extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dbtest);
        Button mybutton = (Button) findViewById(R.id.buttonpress);
        mybutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                TextView txtresp = (TextView)findViewById(R.id.servlet_response);
            String[] args = null;
            try {
                String x = androidconnectors.main(args);
                txtresp.setText(x);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                txtresp.setText("Failed");
            }

            }
        });
}
}

3 个答案:

答案 0 :(得分:2)

基于quick google search,似乎自Honeycomb以来,您不应该在应用程序的主线程上执行网络访问(以提高响应能力)。

按建议here创建另一个网络访问线程。

答案 1 :(得分:2)

您无法在UI线程上进行网络操作,更好地使用AsyncTask/Service/IntentService

<强> NetworkOnMainThreadException

  

应用程序尝试执行时抛出的异常   主线程上的网络操作。(自API 11起)

答案 2 :(得分:1)

要解决StrictMode问题,您需要在活动中使用以下代码 -

static{
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();  
StrictMode.setThreadPolicy(policy);  
}