通过HTTP GET将数据发送到PHP服务器

时间:2016-08-29 23:26:45

标签: java php android

我正在构建一个应用程序,用户可以选择他/她的性别,喜欢的食物,他们的愤怒,喜欢的颜色,他们的年龄等...

我通过Intent将这些数据传递给了我的最终活动。 现在我试图将答案发送到PHP服务器(工作正常)并得到答案(哪个城市最适合你)

这是我的代码,我不知道它有什么问题(我已经添加了连接到互联网的权限) 当我运行应用程序时它工作正常,直到最后一个活动被点击,然后它强制关闭应用程序

public class result extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.result);


    TextView result = (TextView)findViewById(R.id.result);

    final String gender;
    Intent a = getIntent();
    gender = a.getStringExtra("gender");
    final String anger;
    Intent b = getIntent();
    anger = b.getStringExtra("hate");
    final String food;
    Intent c = getIntent();
    food = c.getStringExtra("food");
    final String gettowork;
    Intent d = getIntent();
    gettowork = d.getStringExtra("gotowork");
    final String settelment;
    Intent ee = getIntent();
    settelment = ee.getStringExtra("house");
    final String actor;
    Intent f = getIntent();
    actor = f.getStringExtra("star");
    final String weather;
    Intent g = getIntent();
    weather = g.getStringExtra("weather");
    final String weekend;
    Intent h = getIntent();
    weekend = h.getStringExtra("weekend");
    final String color;
    Intent j = getIntent();
    color = j.getStringExtra("color");
    final String age;
    Intent i10 = getIntent();
    age = i10.getStringExtra("age");


HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://test123.com/games/whichcity/app/check-form.php?gender=" + gender + "&anger=" + anger + "&food=" + food + "&gettowork=" + gettowork + "&settlement=" + settelment + "&actor=" + actor + "&weather=" + weather + "&weekend=" + weekend + "&color=" + color + "&age=" + age);
    HttpResponse response = null;
    try {
        response = httpclient.execute(httpget);
    } catch (IOException e) {
        e.printStackTrace();
    }
    HttpEntity entity = response.getEntity();
    try {
        InputStream webs = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(webs,"iso-8859-1"),8);
        result.setText(reader.readLine());
    } catch (IOException e) {
        e.printStackTrace();



}}}

Android清单文件     

<application

    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".splash_screen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".MainActivity"></activity>
    <activity android:name=".firstquestion"></activity>
    <activity android:name=".secondquestion"></activity>
    <activity android:name=".thirdquestion"></activity>
    <activity android:name=".fourthquestion"></activity>
    <activity android:name=".fifthquestion"></activity>
    <activity android:name=".sixthquestion"></activity>
    <activity android:name=".seventhquestion"></activity>
    <activity android:name=".eighthquestion"></activity>
    <activity android:name=".ninethquestion"></activity>
    <activity android:name=".result"></activity>


</application>

<uses-permission android:name="android.permission.INTERNET" />

我在logcat中的错误:

E/AndroidRuntime: FATAL EXCEPTION: main                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{org.vaya_group.charactertest/org.vaya_group.charactertest.result}: android.os.NetworkOnMainThreadException
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2071)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2096)
                                                                              at android.app.ActivityThread.access$600(ActivityThread.java:138)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1207)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                              at android.os.Looper.loop(Looper.java:213)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:4787)
                                                                              at java.lang.reflect.Method.invokeNative(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:511)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
                                                                              at dalvik.system.NativeStart.main(Native Method)
                                                                           Caused by: android.os.NetworkOnMainThreadException
                                                                              at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1126)
                                                                              at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
                                                                              at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
                                                                              at java.net.InetAddress.getAllByName(InetAddress.java:214)
                                                                              at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:141)
                                                                              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 org.vaya_group.charactertest.result.onCreate(result.java:86)
                                                                              at android.app.Activity.performCreate(Activity.java:5008)
                                                                              at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2035)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2096) 
                                                                              at android.app.ActivityThread.access$600(ActivityThread.java:138) 
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1207) 
                                                                              at android.os.Handler.dispatchMessage(Handler.java:99) 
                                                                              at android.os.Looper.loop(Looper.java:213) 
                                                                              at android.app.ActivityThread.main(ActivityThread.java:4787) 
                                                                              at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                              at java.lang.reflect.Method.invoke(Method.java:511) 
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) 
                                                                              at dalvik.system.NativeStart.main(Native Method) 

1 个答案:

答案 0 :(得分:1)

You are getting this exception because you are attempting to perform a networking operation in UI thread. Instead of this you can have your network operation in another thread or implement some better ways which ultimately put the operation in another thread. These better ways are using AsyncTask or using Volley. I will definitely put my votes for Volley as it is simple and neat.

GET operation implementing volley,

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://test123.com/games/whichcity/app/check-form.php?gender=" + gender + "&anger=" + anger + "&food=" + food + "&gettowork=" + gettowork + "&settlement=" + settelment + "&actor=" + actor + "&weather=" + weather + "&weekend=" + weekend + "&color=" + color + "&age=" + age;

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        //handle response from server
        result.setText(response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        //handle error
        result.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest); 

Inorder to Volley to work, you should add dependency in your gradle. In your Gradle file (Module:app), add compile 'com.android.volley:volley:1.0.0' in dependencies.

dependencies {
    compile 'com.android.volley:volley:1.0.0'
}

Learn more about Volley

Happy coding!