如何制作Android POST HttpURLConnection

时间:2016-12-20 14:07:21

标签: android post httpurlconnection

是的,我知道。我和其他人之前曾问过类似的问题。不过,我正在寻找有关我的具体问题的帮助。我已经将这段代码从其他答案中逐字复制,所以我在这里做错了什么?

public void SendName(View v){
        EditText name = (EditText) findViewById(R.id.name);
        String nombre = name.getText().toString();
        String parameters = "name="+nombre;

        try{
            URL url2 = new URL("*****"); //I've got a correct URL here
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();
            connection.setReadTimeout(15000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");

            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(parameters);
            writer.close();

            os.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

" SendName"函数从布局中的按钮调用onClick。每次我点击该按钮,我的应用程序崩溃。是什么给了什么?

如此说日志:

12-20 09:56:05.630 17593-17593/? D/dalvikvm: Late-enabling CheckJNI
12-20 09:56:05.690 17593-17593/blacktentdigital.com.bintheredumpthatatl D/HyLog: I : /data/font/config/sfconfig.dat, No such file or directory (2)
12-20 09:56:05.690 17593-17593/blacktentdigital.com.bintheredumpthatatl D/HyLog: I : /data/font/config/dfactpre.dat, No such file or directory (2)
12-20 09:56:05.690 17593-17593/blacktentdigital.com.bintheredumpthatatl D/HyLog: I : /data/font/config/sfconfig.dat, No such file or directory (2)
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl I/dalvikvm: Could not find method android.view.Window$Callback.onProvideKeyboardShortcuts, referenced from method android.support.v7.view.WindowCallbackWrapper.onProvideKeyboardShortcuts
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve interface method 19512: Landroid/view/Window$Callback;.onProvideKeyboardShortcuts (Ljava/util/List;Landroid/view/Menu;I)V
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve interface method 19514: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve interface method 19518: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
12-20 09:56:05.760 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve virtual method 476: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
12-20 09:56:05.770 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
12-20 09:56:05.770 17593-17593/blacktentdigital.com.bintheredumpthatatl I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
12-20 09:56:05.770 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve virtual method 498: Landroid/content/res/TypedArray;.getType (I)I
12-20 09:56:05.770 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x6e at 0x0008
12-20 09:56:05.820 17593-17593/blacktentdigital.com.bintheredumpthatatl I/dalvikvm: Could not find method android.widget.FrameLayout.startActionModeForChild, referenced from method android.support.v7.widget.ActionBarContainer.startActionModeForChild
12-20 09:56:05.820 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve virtual method 19990: Landroid/widget/FrameLayout;.startActionModeForChild (Landroid/view/View;Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
12-20 09:56:05.820 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002
12-20 09:56:05.830 17593-17593/blacktentdigital.com.bintheredumpthatatl I/dalvikvm: Could not find method android.content.Context.getColorStateList, referenced from method android.support.v7.content.res.AppCompatResources.getColorStateList
12-20 09:56:05.830 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve virtual method 290: Landroid/content/Context;.getColorStateList (I)Landroid/content/res/ColorStateList;
12-20 09:56:05.830 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
12-20 09:56:05.840 17593-17593/blacktentdigital.com.bintheredumpthatatl I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
12-20 09:56:05.850 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve virtual method 439: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
12-20 09:56:05.850 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
12-20 09:56:05.850 17593-17593/blacktentdigital.com.bintheredumpthatatl I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
12-20 09:56:05.850 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve virtual method 441: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
12-20 09:56:05.850 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
12-20 09:56:05.860 17593-17593/blacktentdigital.com.bintheredumpthatatl E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
12-20 09:56:05.860 17593-17593/blacktentdigital.com.bintheredumpthatatl W/dalvikvm: VFY: unable to resolve instanceof 141 (Landroid/graphics/drawable/RippleDrawable;) in Landroid/support/v7/widget/AppCompatImageHelper;
12-20 09:56:05.860 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: VFY: replacing opcode 0x20 at 0x000c
12-20 09:56:05.910 17593-17593/blacktentdigital.com.bintheredumpthatatl D/dalvikvm: GC_FOR_ALLOC freed 227K, 6% free 4729K/5016K, paused 16ms, total 16ms
12-20 09:56:05.980 17593-17593/blacktentdigital.com.bintheredumpthatatl I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.089_msm8610_KK_3.5_RB1__release_AU ()
                                                                                      OpenGL ES Shader Compiler Version: E031.24.00.06
                                                                                      Build Date: 01/30/14 Thu
                                                                                      Local Branch: 
                                                                                      Remote Branch: quic/kk_3.5_rb1.21
                                                                                      Local Patches: NONE
                                                                                      Reconstruct Branch: AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.089 +  NOTHING
12-20 09:56:06.010 17593-17593/blacktentdigital.com.bintheredumpthatatl D/OpenGLRenderer: Enabling debug mode 0
12-20 09:56:06.540 17593-17593/blacktentdigital.com.bintheredumpthatatl I/ActivityManager: Timeline: Activity_idle id: android.os.BinderProxy@41c00770 time:6431179
12-20 09:56:13.060 17593-17593/blacktentdigital.com.bintheredumpthatatl W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
12-20 09:56:13.060 17593-17593/blacktentdigital.com.bintheredumpthatatl I/ActivityManager: Timeline: Activity_idle id: android.os.BinderProxy@41c00770 time:6437691
12-20 09:56:13.080 17593-17593/blacktentdigital.com.bintheredumpthatatl W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
12-20 09:56:13.530 17593-17593/blacktentdigital.com.bintheredumpthatatl W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
12-20 09:56:13.800 17593-17593/blacktentdigital.com.bintheredumpthatatl I/ActivityManager: Timeline: Activity_idle id: android.os.BinderProxy@41c00770 time:6438430

1 个答案:

答案 0 :(得分:0)

// I had use this code it is working fine for me try this one 

public class JsonParser {

    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }

            try {
                urlObj = new URL(url);

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

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

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            Log.d("JSON Parser", "result: " + result.toString());

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

        conn.disconnect();

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

        // return JSON Object
        return jObj;
    }
}