Reputation: 1957
I am sending a server request with javacode in android but i am getting response code as 414. I am new to android. Please help. I am using a post method.I am using the following code:
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;
}
}
My url request is this:
jsonObject=JSONfunctions.getJSONfromURL("http://54.169.88.65/events/eventmain/get_users.php?json="+URLencoded);
URLencoded
is json data converted into string and then urlencoded.
Upvotes: 2
Views: 5283
Reputation: 1764
First of all, as any 4xx error code suggests, it has something to do on the client's end, and not server side.
As you are getting 414, means that the URL you are hitting is too long.
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.
Reference: here
This suggests me, that the string you are appending to the "?json=" ending is way too long, and you possibly should not pass it in the URL. I can also see, that you are trying to POST request, even thought the practice you are doing there has nothing to do with POST. You are making a GET request with a query string.
So depending how the service is designed, if it takes in a query string you cannot do much besides making sure you can fit into the valid URL limit set on the server.
If the service is designed to take POST requests (it really should, as I can tell in this case!), then you should implement a proper POST request with a body saying:
json = "{your-valid-json-here}"
I suggest you look into the Framework provided by Google, called Volley and try to implement in an AsyncTask (if needed), to be able to act on the response:
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);
}
This examples presumes the following:
Upvotes: 3