从try catch块返回字符串

时间:2015-04-28 21:04:28

标签: java android http try-catch

我正在尝试从Foo函数返回字符串,但应用程序崩溃了。

public String Foo (String email){
    String url_set = "http://****.php?email=" + email;
    String responseStr = "1";
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url_set);
        HttpResponse response = httpClient.execute(httpPost);
        return responseStr;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return responseStr;
    } catch (ClientProtocolException e) {
        Log.e("ClientProtocolException", "Client");
        e.printStackTrace();
        return responseStr;
    } catch (IOException e) {
        Log.e("Ioexception", "Ioexption");
        e.printStackTrace();
        return responseStr;
    }
}

一般情况下,我想将响应转换为字符串并将其返回给调用者。 但是现在我不能回信。

UPD:logcat

04-28 14:13:57.220    2917-2917/com.example.lemon.onlineshop E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.lemon.onlineshop, PID: 2917
    android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
            at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
            at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
            at java.net.InetAddress.getAllByName(InetAddress.java:215)
            at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
            at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
            at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
            at com.example.lemon.onlineshop.Library.SessionManager.getString(SessionManager.java:88)
            at com.example.lemon.onlineshop.Library.SessionManager.createLoginSession(SessionManager.java:76)
            at com.example.lemon.onlineshop.MainActivity.executeLogIn(MainActivity.java:96)
            at com.example.lemon.onlineshop.MainActivity$LogIn.onPostExecute(MainActivity.java:191)
            at com.example.lemon.onlineshop.MainActivity$LogIn.onPostExecute(MainActivity.java:160)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

UPD2:增加全班

public class SessionManager {
// Shared Preferences
SharedPreferences pref;

// Editor for Shared preferences
SharedPreferences.Editor editor;

// Context
Context _context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Sharedpref file name
private static final String PREF_NAME = "SessionPref";

// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";

// User name (make variable public to access from outside)
public static final String KEY_EMAIL = "email";

// Email address (make variable public to access from outside)
public static final String KEY_PASSWORD = "password";

//
public static final String KEY_ID = "id";

// Constructor
public SessionManager(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

/**
 * Create login session
 * */
public void createLoginSession(String email, String password){
    // Storing login value as TRUE
    editor.putBoolean(IS_LOGIN, true);

    // Storing name in pref
    editor.putString(KEY_EMAIL, email);

    // Storing email in pref
    editor.putString(KEY_PASSWORD, password);

    // Storing id in pref
    editor.putString(KEY_ID, getId(email));
    // commit changes
    editor.commit();
}

public String getId(String email){
    String url_set = "http://***.php?email=" + email;
    String responseStr = "1";
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url_set);
        httpClient.execute(httpPost);
        return responseStr;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return responseStr;
    } catch (ClientProtocolException e) {
        Log.e("ClientProtocolException", "Client");
        e.printStackTrace();
        return responseStr;
    } catch (IOException e) {
        Log.e("Ioexception", "Ioexption");
        e.printStackTrace();
        return responseStr;
    }
}

1 个答案:

答案 0 :(得分:1)

您无法在主线程上进行网络呼叫。您需要创建一个单独的线程来运行此功能。