HTTP 错误 414。在 android 中通过 java 向服务器传递数据时请求 URL 太长

HTTP Error 414. The request URL is too long while passing data to server through java in android

我正在 android 中使用 javacode 发送服务器请求,但我收到的响应代码为 414。我是 android 的新手。请帮忙。我正在使用 post method.I 我正在使用以下代码:

package com.hfad.evenit;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Vicky on 22-Jul-15.
 */
public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url1) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;
        int response=0;
        // Download JSON data from URL
        try {

            URL url = new URL(url1);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            response = conn.getResponseCode();
            is = new BufferedInputStream(conn.getInputStream());

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
            Log.e("log_tag", "Response  " + response);
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

我的url请求是这样的:

jsonObject=JSONfunctions.getJSONfromURL("http://54.169.88.65/events/eventmain/get_users.php?json="+URLencoded);

URLencoded是json数据转成字符串然后url编码。

首先,正如任何 4xx 错误代码所暗示的那样,它与客户端有关,与服务器端无关。

当你得到 414 时,意味着你打的 URL 太长了。

414 - Request-URL Too Long The web server responds with this error when it is refusing to service the request because the Request-URL is longer than the server is willing or able to interpret. This rare condition is only likely to occur when a client has improperly converted a POST request to a GET request with long query information, when the client has descended into a URL "black hole" of redirection (e.g., a redirected URL prefix that points to a suffix of itself), or when the server is under attack by a client attempting to exploit security holes present in some servers using fixed-length buffers for reading or manipulating the Request-URL. Typically Web servers set fairly generous limits on length for genuine URLs e.g. up to 2048 or 4096 characters. If a long URL is valid and you receive 414 errors, then the Web server may need to be reconfigured to allow such URLs through.

参考:here

这表明我,您附加到“?json=”结尾的字符串太长,您可能不应该在 URL 中传递它。我还看到,你在尝试 POST 请求,甚至认为你在那里做的练习与 POST 无关。您正在使用 query string.

发出 GET 请求

因此,根据服务的设计方式,如果它接受查询字符串,除了确保您可以符合服务器上设置的有效 URL 限制外,您无能为力。

如果该服务旨在接受 POST 请求(它确实应该,正如我在这种情况下所知道的那样!),那么您应该实施一个适当的 POST 请求,其正文如下:

json = "{your-valid-json-here}"

我建议您查看 Google 提供的框架,称为 Volley 并尝试在 AsyncTask 中实施(如果需要),以便能够对响应采取行动:

MainActivity.java

package me.monori.examples.post.activities;

import android.app.Activity;
import android.os.Bundle;

import me.monori.examples.post;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        // This is where you call your service
        new PostExampleAsync(this).execute();
    }
    //...//
}

PostExampleAsync.java

package me.monori.examples.post;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import me.monori.examples.post.interfaces.onServiceCallCompleted;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Antal Janos Monori on 10-05-2015.
 * Copyright 2015 monori.me. All rights reserved.
 */
public class PostExampleAsync extends AsyncTask<String, Boolean, Boolean> implements onServiceCallCompleted
{
    private static final String TAG = "PostExampleAsync";
    private Activity mActivity;
    private onServiceCallCompleted mListener;
    private static final String URL = "http://54.169.88.65/events/eventmain/get_users.php";

    public PostExampleAsync(Activity act)
    {
        this.mActivity = act;
        this.mListener = this;
    }

    @Override
    protected Boolean doInBackground(final String... params)
    {
        final String url = mMyPrefs.getString(URL, "");

        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(mActivity);

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response)
                {
                    Log.d(TAG, "Response from Service received");
                    // First validation
                    try
                    {
                        JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                        // Call onServiceCallComplete
                        mListener.onServiceCallComplete(jsonObject);
                    }
                    catch (JsonParseException e)
                    {
                        // @TODO: Catch the case when we get back something other than a valid Json
                        Log.e(TAG, e.getMessage());
                    }
                }
            }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                // @TODO: Catch error and print out proper message.
                Log.e(TAG, "Something went wrong");
            }
        })
        {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> postParams = new HashMap<>();
                if (params.length > 0)
                {
                    postParams.put("json", params[0]);
                }
                return postParams;
            }
        };
        // Add the request to the RequestQueue.
        queue.add(stringRequest);

        return true;
    }

    @Override
    public boolean onServiceCallComplete(JsonObject response)
    {
        String responseString = response.toString();

        // @TODO: Do something with the results here

        return true;
    }
}

onServiceCallCompleted.java

package me.monori.examples.post.interfaces;

import com.google.gson.JsonObject;

/**
 * Created by Antal Janos Monori on 10-05-2015.
 * Copyright 2015 monori.me. All rights reserved.
 */
public interface onServiceCallCompleted {
    /**
     * A method call, that is triggered when a service call is finished, by a class that implements this interface.
     * @param response The raw String response from the service
     * @return boolean true if successful, false otherwise
     */
    boolean onServiceCallComplete(JsonObject response);
}

备注

此示例假设如下:

  • 您想发送 POST 请求而不是 GET 请求;如果是其他情况,请查看 Volley documentation 了解如何更改。
  • 您期望服务的响应(不仅仅是发送 JSON 字符串
  • 您想 运行 它在异步任务中。
  • 您下载并实现了 Volley 库。