我是Android开发者的初学者。我想从服务器,方法 - Post获取一些数据。据我所知,我需要做请求,而不是我需要将HttpEntity转换为字符串,然后将字符串转换为json。活动文件代码:
package com.example.earchive;
import java.io.IOException;
import java.util.ArrayList;
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.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
/*** Work with login button ***/
final Button button = (Button) findViewById(R.id.login_bt);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://go.earchive.ca/json/user.php");
try
{
EditText email = (EditText)findViewById(R.id.email);
EditText password = (EditText)findViewById(R.id.password);
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("em", email.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pa", password.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
try {
JSONObject obj = new JSONObject(result);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + result + "\"");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
//System.out.println(Arrays.toString(response));
}
});
/*** End of work with login button ***/
return true;
}
}
XML文件的代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bkg_2"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".LoginActivity" >
<EditText
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/password"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/password"
android:layout_marginTop="162dp"
android:background="@color/white"
android:ems="10"
android:inputType="textEmailAddress"
android:padding="5px" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:src="@drawable/lettera" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imageView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:src="@drawable/scritta" />
<EditText
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@color/white"
android:ems="10"
android:inputType="textPassword"
android:padding="5px" />
<Button
android:id="@+id/login_bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/password"
android:layout_alignRight="@+id/password"
android:layout_below="@+id/password"
android:layout_marginTop="16dp"
android:text="Login"
android:background="@color/red"
android:textColor="@color/white"
/>
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/imageView2"
android:layout_below="@+id/button1"
android:layout_marginTop="16dp"
android:text="Remember me"
android:checked="true"
/>
</RelativeLayout>
输出:
02-11 10:19:10.378: D/dalvikvm(1302): GC_FOR_ALLOC freed 56K, 4% free 3327K/3452K, paused 31ms, total 33ms
02-11 10:19:10.788: D/gralloc_goldfish(1302): Emulator without GPU emulation detected.
02-11 10:19:23.398: D/InputEventConsistencyVerifier(1302): KeyEvent: ACTION_UP but key was not down.
02-11 10:19:23.398: D/InputEventConsistencyVerifier(1302): in android.widget.EditText{b1e49448 VFED..CL .F....I. 179,489-589,548 #7f090001 app:id/password}
02-11 10:19:23.398: D/InputEventConsistencyVerifier(1302): 0: sent at 1624812000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=1624812, downTime=1624667, deviceId=0, source=0x101 }
02-11 10:19:24.318: D/dalvikvm(1302): GC_FOR_ALLOC freed 153K, 6% free 3688K/3908K, paused 34ms, total 39ms
02-11 10:19:26.638: D/AndroidRuntime(1302): Shutting down VM
02-11 10:19:26.638: W/dalvikvm(1302): threadid=1: thread exiting with uncaught exception (group=0xb1afbba8)
02-11 10:19:26.658: E/AndroidRuntime(1302): FATAL EXCEPTION: main
02-11 10:19:26.658: E/AndroidRuntime(1302): Process: com.example.earchive, PID: 1302
02-11 10:19:26.658: E/AndroidRuntime(1302): android.os.NetworkOnMainThreadException
02-11 10:19:26.658: E/AndroidRuntime(1302): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
02-11 10:19:26.658: E/AndroidRuntime(1302): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
02-11 10:19:26.658: E/AndroidRuntime(1302): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
02-11 10:19:26.658: E/AndroidRuntime(1302): at java.net.InetAddress.getAllByName(InetAddress.java:214)
02-11 10:19:26.658: E/AndroidRuntime(1302): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
02-11 10:19:26.658: E/AndroidRuntime(1302): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-11 10:19:26.658: E/AndroidRuntime(1302): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-11 10:19:26.658: E/AndroidRuntime(1302): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-11 10:19:26.658: E/AndroidRuntime(1302): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-11 10:19:26.658: E/AndroidRuntime(1302): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-11 10:19:26.658: E/AndroidRuntime(1302): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-11 10:19:26.658: E/AndroidRuntime(1302): at com.example.earchive.LoginActivity$1.onClick(LoginActivity.java:65)
02-11 10:19:26.658: E/AndroidRuntime(1302): at android.view.View.performClick(View.java:4438)
02-11 10:19:26.658: E/AndroidRuntime(1302): at android.view.View$PerformClick.run(View.java:18422)
02-11 10:19:26.658: E/AndroidRuntime(1302): at android.os.Handler.handleCallback(Handler.java:733)
02-11 10:19:26.658: E/AndroidRuntime(1302): at android.os.Handler.dispatchMessage(Handler.java:95)
02-11 10:19:26.658: E/AndroidRuntime(1302): at android.os.Looper.loop(Looper.java:136)
02-11 10:19:26.658: E/AndroidRuntime(1302): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-11 10:19:26.658: E/AndroidRuntime(1302): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 10:19:26.658: E/AndroidRuntime(1302): at java.lang.reflect.Method.invoke(Method.java:515)
02-11 10:19:26.658: E/AndroidRuntime(1302): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-11 10:19:26.658: E/AndroidRuntime(1302): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-11 10:19:26.658: E/AndroidRuntime(1302): at dalvik.system.NativeStart.main(Native Method)
我的方式是否正确? 感谢所有
答案 0 :(得分:1)
因为你在主线程上进行网络操作。只需做一个AsyncTask就可以了。