Android的发送后数据web服务 [英] Android sending post data to webservice

查看:188
本文介绍了Android的发送后数据web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我试图将数据发送到一个web服务

字符串URL = https://www.myurl.com ;

  URL urlobj =新的URL(网址);
    HttpsURLConnection的CON =(HttpsURLConnection的)urlobj.openConnection();
    con.setRequestMethod(POST);
    con.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);    串urlParameters = GenerateUrlParameters(数据);    con.setDoOutput(真);
    con.setDoInput(真);    Log.i(测试,HIT1);    DataOutputStream类WR =新的DataOutputStream类(con.getOutputStream());    Log.i(测试,HIT2);    wr.writeBytes(urlParameters);    wr.flush();
    wr.close();

HIT1被击中,但在接下来的线路出现故障,不打HIT2。我在做什么错了?

我的logcat

  9月10日至18日:17:33.302:D / gralloc_goldfish(2228):无仿真模拟GPU检测。
九月10日至18日:17:33.322:W / TextLayoutCache(2228):computeValues​​WithHarfbuzz - 需要强制单次运行
九月10日至18日:17:37.862:I /试验(2228):HIT1
九月10日至18日:17:37.872:D / AndroidRuntime(2228):关闭VM
九月10日至18日:17:37.872:W / dalvikvm(2228):主题ID = 1:螺纹未捕获的异常(组= 0x409961f8)退出
九月10日至18日:17:37.912:E / AndroidRuntime(2228):致命异常:主要
九月10日至18日:17:37.912:E / AndroidRuntime(2228):java.lang.IllegalStateException:无法执行活动的方法
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在android.view.View $ 1.onClick(View.java:3039)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在android.view.View.performClick(View.java:3480)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在android.view.View $ PerformClick.run(View.java:13983)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在android.os.Handler.handleCallback(Handler.java:605)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在android.os.Handler.dispatchMessage(Handler.java:92)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在android.os.Looper.loop(Looper.java:137)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在android.app.ActivityThread.main(ActivityThread.java:4340)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在java.lang.reflect.Method.invokeNative(本机方法)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在java.lang.reflect.Method.invoke(Method.java:511)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在dalvik.system.NativeStart.main(本机方法)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):因:java.lang.reflect.InvocationTargetException
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在java.lang.reflect.Method.invokeNative(本机方法)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在java.lang.reflect.Method.invoke(Method.java:511)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在android.view.View $ 1.onClick(View.java:3034)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):11 ...更多
九月10日至18日:17:37.912:E / AndroidRuntime(2228):因:android.os.NetworkOnMainThreadException
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在java.net.InetAddress.lookupHostByName(InetAddress.java:391)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在java.net.InetAddress.getAllByName(InetAddress.java:220)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpConnection<&初始化GT;(HttpConnection.java:71)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpConnection<&初始化GT;(HttpConnection.java:50)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpConnection $ Address.connect(HttpConnection.java:351)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:460)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpsURLConnectionImpl $ HttpsEngine.connect(HttpsURLConnectionImpl.java:432)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在libcore.net.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:280)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在dk.example.epaypayment.EpayHtt prequest.MakePayment(EpayHtt prequest.java:53)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):在dk.example.epaypayment.MainActivity.sendMessage(MainActivity.java:37)
九月10日至18日:17:37.912:E / AndroidRuntime(2228):14 ...更多
九月10日至18日:22:38.232:I /流程(2228):发送信号。 PID:2228 SIG:9


解决方案

呼叫 sendPostRequest(字符串username,字符串传递)法的参数。您还可以从UI线程这种方法,请求将来自不同的线程中发送(的AsyncTask 嵌入)。

 私人无效sendPostRequest(字符串givenUsername,字符串givenPassword){    类SendPostReqAsyncTask扩展的AsyncTask<弦乐,太虚,字符串> {        @覆盖
        保护字符串doInBackground(字符串... PARAMS){
            串paramUsername =参数[0];
            串paramPassword =参数[1];            的System.out.println(*** doInBackground ** paramUsername
                + paramUsername +paramPassword:+ paramPassword);            HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httpPost =新HttpPost(
                http://lib-dm.process9.com/libertydm/ValidateUserHandler.ashx\");//与您的网址替换
            httpPost.addHeader(内容类型,
                应用程序/ x-WWW的形式urlen codeD);
            BasicNameValuePair usernameBasicNameValuePair =新BasicNameValuePair(
                用户ID,paramUsername); //使自己的键值对
            BasicNameValuePair passwordBasicNameValuePAir =新BasicNameValuePair(
                密码,paramPassword); //使自己的键值对            //你可以添加更多的参数,如上面            清单<&的NameValuePair GT; nameValuePairList =新的ArrayList<&的NameValuePair GT;();
            nameValuePairList.add(usernameBasicNameValuePair);
            nameValuePairList.add(passwordBasicNameValuePair);            尝试{
                UrlEn codedFormEntity urlEn codedFormEntity =新UrlEn codedFormEntity(
                    nameValuePairList);
                httpPost.setEntity(urlEn codedFormEntity);                尝试{
                    HTT presponse HTT presponse =的HttpClient
                        .execute(httpPost);
                    为InputStream的InputStream = HTT presponse.getEntity()
                        .getContent();
                    InputStreamReader的InputStreamReader的=新的InputStreamReader(
                        InputStream的);
                    的BufferedReader的BufferedReader =新的BufferedReader(
                        InputStreamReader的);
                    StringBuilder的StringBuilder的=新的StringBuilder();
                    字符串bufferedStrChunk = NULL;
                    而((bufferedStrChunk = bufferedReader.readLine())!= NULL){
                        stringBuilder.append(bufferedStrChunk);
                    }                    返回stringBuilder.toString();                    }赶上(ClientProtocolException CPE){
                        System.out的
                            .println(Htt的presponese的第一个例外正版游戏:
                                + CPE);
                        cpe.printStackTrace();
                    }赶上(IOException异常IOE){
                        System.out的
                            .println(Htt的presponse的第二个例外正版游戏:
                                + IOE);
                        ioe.printStackTrace();
                    }            }赶上(UnsupportedEncodingException UEE){
                System.out的
                    .println(一个例外,因为给出UrlEn codedFormEntity说法:
                        UEE +);
                uee.printStackTrace();
            }
            返回null;
        }        @覆盖
        保护无效onPostExecute(字符串结果){
            super.onPostExecute(结果);
        }
    }    SendPostReqAsyncTask sendPostReqAsyncTask =新SendPostReqAsyncTask();
    sendPostReqAsyncTask.execute(givenUsername,givenPassword);
}

Hi I'm trying to send data to a webservice

String url = "https://www.myurl.com";

    URL urlobj =  new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) urlobj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    String urlParameters = GenerateUrlParameters(data);

    con.setDoOutput(true);
    con.setDoInput(true);

    Log.i("test", "hit1");

    DataOutputStream  wr = new DataOutputStream(con.getOutputStream());

    Log.i("test", "hit2");

    wr.writeBytes(urlParameters);

    wr.flush();
    wr.close();

Hit1 is hit but it fails in the next line and doesn't hit hit2. What am I doing wrong ?

My logcat

10-18 09:17:33.302: D/gralloc_goldfish(2228): Emulator without GPU emulation detected.
10-18 09:17:33.322: W/TextLayoutCache(2228): computeValuesWithHarfbuzz -- need to force to single run
10-18 09:17:37.862: I/test(2228): hit1
10-18 09:17:37.872: D/AndroidRuntime(2228): Shutting down VM
10-18 09:17:37.872: W/dalvikvm(2228): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
10-18 09:17:37.912: E/AndroidRuntime(2228): FATAL EXCEPTION: main
10-18 09:17:37.912: E/AndroidRuntime(2228): java.lang.IllegalStateException: Could not execute method of the activity
10-18 09:17:37.912: E/AndroidRuntime(2228):     at android.view.View$1.onClick(View.java:3039)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at android.view.View.performClick(View.java:3480)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at android.view.View$PerformClick.run(View.java:13983)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at android.os.Handler.handleCallback(Handler.java:605)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at android.os.Looper.loop(Looper.java:137)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at android.app.ActivityThread.main(ActivityThread.java:4340)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at java.lang.reflect.Method.invokeNative(Native Method)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at java.lang.reflect.Method.invoke(Method.java:511)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at dalvik.system.NativeStart.main(Native Method)
10-18 09:17:37.912: E/AndroidRuntime(2228): Caused by: java.lang.reflect.InvocationTargetException
10-18 09:17:37.912: E/AndroidRuntime(2228):     at java.lang.reflect.Method.invokeNative(Native Method)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at java.lang.reflect.Method.invoke(Method.java:511)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at android.view.View$1.onClick(View.java:3034)
10-18 09:17:37.912: E/AndroidRuntime(2228):     ... 11 more
10-18 09:17:37.912: E/AndroidRuntime(2228): Caused by: android.os.NetworkOnMainThreadException
10-18 09:17:37.912: E/AndroidRuntime(2228):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:460)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:432)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at libcore.net.http.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:280)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at dk.example.epaypayment.EpayHttpRequest.MakePayment(EpayHttpRequest.java:53)
10-18 09:17:37.912: E/AndroidRuntime(2228):     at dk.example.epaypayment.MainActivity.sendMessage(MainActivity.java:37)
10-18 09:17:37.912: E/AndroidRuntime(2228):     ... 14 more
10-18 09:22:38.232: I/Process(2228): Sending signal. PID: 2228 SIG: 9

解决方案

Call sendPostRequest(String username, String pass) method with parameters. You can call this method from the UI thread, the request will be sent from a different thread (AsyncTask is embedded).

private void sendPostRequest(String givenUsername, String givenPassword) {

    class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String paramUsername = params[0];
            String paramPassword = params[1];

            System.out.println("*** doInBackground ** paramUsername "
                + paramUsername + " paramPassword :" + paramPassword);

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(
                "http://lib-dm.process9.com/libertydm/ValidateUserHandler.ashx");// replace with your url
            httpPost.addHeader("Content-type",
                "application/x-www-form-urlencoded");
            BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair(
                "UserId", paramUsername);  // Make your own key value pair
            BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair(
                "Password", paramPassword);// make your own key value pair

            // You can add more parameters like above

            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
            nameValuePairList.add(usernameBasicNameValuePair);
            nameValuePairList.add(passwordBasicNameValuePair);

            try {
                UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
                    nameValuePairList);
                httpPost.setEntity(urlEncodedFormEntity);

                try {
                    HttpResponse httpResponse = httpClient
                        .execute(httpPost);
                    InputStream inputStream = httpResponse.getEntity()
                        .getContent();
                    InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream);
                    BufferedReader bufferedReader = new BufferedReader(
                        inputStreamReader);
                    StringBuilder stringBuilder = new StringBuilder();
                    String bufferedStrChunk = null;
                    while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                        stringBuilder.append(bufferedStrChunk);
                    }

                    return stringBuilder.toString();

                    } catch (ClientProtocolException cpe) {
                        System.out
                            .println("First Exception coz of HttpResponese :"
                                + cpe);
                        cpe.printStackTrace();
                    } catch (IOException ioe) {
                        System.out
                            .println("Second Exception coz of HttpResponse :"
                                + ioe);
                        ioe.printStackTrace();
                    }

            } catch (UnsupportedEncodingException uee) {
                System.out
                    .println("An Exception given because of UrlEncodedFormEntity argument :"
                        + uee);
                uee.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
    sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}

这篇关于Android的发送后数据web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆