Android HTTP请求甚至在发出请求之前崩溃应用程序

时间:2012-10-03 00:24:22

标签: android apache-httpclient-4.x

  

可能重复:
  Android HttpClient : NetworkOnMainThreadException

我正在处理正在发出请求的应用程序,并且应用程序运行正常,直到我必须向服务器发出请求。我使用的代码与之前为同一个应用程序编写的代码相同,但这已经过修改。

处理点击的片段类:

import org.json.JSONException;
import org.json.JSONObject;
import org.myapp.app.utils.API;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class FragmentStudentLogin extends Fragment implements OnClickListener {
EditText uN, pW;
Button signin;

private API api;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.fragment_login, container, false);
    signin = (Button)v.findViewById(R.id.s_sign_in);
    signin.setOnClickListener(this);

    uN = (EditText)v.findViewById(R.id.f_t_s_username);
    pW = (EditText)v.findViewById(R.id.f_t_s_password);

    api = new API();

    return v;

    }

    public void onClick(View v){
    switch(v.getId())
    {
        case R.id.s_sign_in:
            String user = uN.getText().toString();
            String pass = pW.getText().toString();
            if(user.length()==0){
                PopIt("Please enter your username.");
            } else if(pass.length()==0){
                PopIt("Please enter your password.");
            } else {
                try {
            JSONObject json;
                    json = api.login(user, pass);
        if(json == null || json.isNull("status")){
            PopIt(getString(R.string.error_network));
        } else {
                        PopIt(json.getString("msg"));
                    }
                } catch (JSONException e){ }
            }
        break;
        }
    }

    public void PopIt(String msg){
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }
}

Click的类调用:

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import org.myapp.app.utils.JSONParser;

public class API
{
    private JSONParser jsonParser;
    private static String serverURL = "http://mydomain.com/api/device/login";

    public API(){
        jsonParser = new JSONParser();
    }

    public JSONObject login(String uN, String pW)
    {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", uN));
        params.add(new BasicNameValuePair("password", pW));
        JSONObject json = jsonParser.getJSONFromUrl(serverURL, params);
        return json;
    }

处理请求的类:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

 // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

logcat的

10-02 19:40:23.734: E/AndroidRuntime(4401): FATAL EXCEPTION: main
10-02 19:40:23.734: E/AndroidRuntime(4401): android.os.NetworkOnMainThreadException
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.myapp.app.utils.JSONParser.getJSONFromUrl(JSONParser.java:42)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.myapp.app.utils.API.studentLogin(API.java:26)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at org.myapp.app.FragmentStudentLogin.onClick(FragmentStudentLogin.java:52)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.view.View.performClick(View.java:3511)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.view.View$PerformClick.run(View.java:14109)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.Handler.handleCallback(Handler.java:605)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.os.Looper.loop(Looper.java:137)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at android.app.ActivityThread.main(ActivityThread.java:4424)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.lang.reflect.Method.invokeNative(Native Method)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at java.lang.reflect.Method.invoke(Method.java:511)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-02 19:40:23.734: E/AndroidRuntime(4401):     at dalvik.system.NativeStart.main(Native Method)

就像我说的那样,这段代码以前工作过,“Click of Click调用:”和“Class that Processes Requests:”部分,我之前使用过没有任何问题。 Android API 16正在7英寸平板电脑上使用。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

异常消息非常清楚。 Android 4.0及更高版本不允许您在主(UI)线程上进行网络调用。