【问题标题】:How to work with HTTP Post in android?如何在 Android 中使用 HTTP Post?
【发布时间】:2015-02-13 07:58:17
【问题描述】:

我是 android 新手,我正在关注可用的简单示例代码 http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89 以下是源代码:

public class HTTPPostEx extends ActionBarActivity {

    TextView content;
    EditText fname, email, login, pass;
    String Name, Email, Login, Pass;    

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_httppost_ex);

        content    =   (TextView)findViewById( R.id.textView6);
        fname      =   (EditText)findViewById(R.id.editText);
        email      =   (EditText)findViewById(R.id.editText2);
        login      =    (EditText)findViewById(R.id.editText3);
        pass       =   (EditText)findViewById(R.id.editText4);


        Button saveme=(Button)findViewById(R.id.button);

        saveme.setOnClickListener(new Button.OnClickListener(){

            public void onClick(View v)
            {
                try{   

                    GetText();
                }
                catch(Exception ex)
                {
                    content.setText(" url exeption! " );
                }
            }
        });
    }   

    public  void  GetText()  throws UnsupportedEncodingException
    {          
        Name = fname.getText().toString();
        Email   = email.getText().toString();
        Login   = login.getText().toString();
        Pass   = pass.getText().toString();

        // Create data variable for sent values to server

        String data = URLEncoder.encode("name", "UTF-8")+ "=" + URLEncoder.encode(Name, "UTF-8");

        data += "&" + URLEncoder.encode("email", "UTF-8")+ "=" + URLEncoder.encode(Email, "UTF-8");

        data += "&" + URLEncoder.encode("user", "UTF-8")+ "=" + URLEncoder.encode(Login, "UTF-8");

        data += "&" + URLEncoder.encode("pass", "UTF-8")+ "=" + URLEncoder.encode(Pass, "UTF-8");

        String text = "";
        BufferedReader reader=null;

        // Send data
        try
        {  

            URL url = new URL("http://androidexample.com/media/webservice/httppost.php");


            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write( data );
            wr.flush();

            // Get the server response

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

           while((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }


            text = sb.toString();
        }
        catch(Exception ex)
        {

        }
        finally
        {
            try
            {

                reader.close();
            }

            catch(Exception ex) {}
        }

        content.setText( text  );

    }}

这段代码没有任何问题。但我无法在网络上发布数据。 这是 logcat 的输出:

    02-13 14:10:04.986  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
02-13 14:10:04.986  22550-22550/com.funkiorangetech.httppostexample E/error﹕ android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
            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 libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
            at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
            at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
            at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
            at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
            at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
            at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
            at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
            at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
            at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
            at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
            at com.funkiorangetech.httppostexample.HTTPPostEx.GetText(HTTPPostEx.java:93)
            at com.funkiorangetech.httppostexample.HTTPPostEx$1.onClick(HTTPPostEx.java:48)
            at android.view.View.performClick(View.java:4432)
            at android.view.View$PerformClick.run(View.java:18338)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5283)
            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:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)
02-13 14:10:04.986  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ java.lang.NullPointerException
02-13 14:10:04.986  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at com.funkiorangetech.httppostexample.HTTPPostEx.GetText(HTTPPostEx.java:124)
02-13 14:10:04.986  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at com.funkiorangetech.httppostexample.HTTPPostEx$1.onClick(HTTPPostEx.java:48)
02-13 14:10:04.986  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at android.view.View.performClick(View.java:4432)
02-13 14:10:04.986  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at android.view.View$PerformClick.run(View.java:18338)
02-13 14:10:04.986  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:725)
02-13 14:10:04.986  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
02-13 14:10:04.996  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
02-13 14:10:04.996  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5283)
02-13 14:10:04.996  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
02-13 14:10:04.996  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
02-13 14:10:04.996  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
02-13 14:10:04.996  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
02-13 14:10:04.996  22550-22550/com.funkiorangetech.httppostexample W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
02-13 14:10:04.996  22550-22550/com.funkiorangetech.httppostexample E/error﹕ java.lang.NullPointerException
            at com.funkiorangetech.httppostexample.HTTPPostEx.GetText(HTTPPostEx.java:124)
            at com.funkiorangetech.httppostexample.HTTPPostEx$1.onClick(HTTPPostEx.java:48)
            at android.view.View.performClick(View.java:4432)
            at android.view.View$PerformClick.run(View.java:18338)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5283)
            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:1102)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
            at dalvik.system.NativeStart.main(Native Method)

请任何人帮助我了解它是如何工作的。提前致谢。

【问题讨论】:

  • text = sb.toString(); 得到什么回应?
  • @ρяσѕρєяK-我什么也没得到:(
  • 看看这个code
  • @Param : neither i am getting error on button click 因为您正在捕获Exception 异常并且没有在任何catch 块中使用ex.printStackTrace();,这就是日志中未显示错误的原因。添加ex.printStackTrace(); 每个catch 块以获取异常日志
  • @JoanColmenero- 是的,这段代码很简单,但我的代码呢?它出什么问题了?你能解释一下吗?是不是走错路了?

标签: php android http-post


【解决方案1】:

【讨论】:

  • 我用了同样的例子:(
  • 但是它已经尝试过这个例子它工作得很好......重新检查代码。
【解决方案2】:

我知道我收到此错误的原因。我刚刚查看了this link 并知道我不应该使用这样的代码。相反,我应该使用 Thread 和处理程序来处理 HTTP 调用。好吧,谢谢大家的帮助。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 2013-10-12
    • 2015-10-20
    相关资源
    最近更新 更多