Http 500 Internal Server Error in Android - java

Android code
class BirthdayTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
System.out.println(uri[0]);
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
System.out.println("responseString"+responseString);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (Exception e) {
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
/* System.out.println(result);
System.out.println(result);
System.out.println(result);*/
}
}
#RequestMapping(value="here is my url" ,method=RequestMethod.GET)
public #ResponseBody String Test(HttpServletRequest req) {
Gson gson = new Gson();
Domain domain = (Domain)req.getSession().getAttribute("Domain");
List<UserProfile> userProfiles = userProfileManager.getUpcomingBirthday(domain.getDomainId(),15);
return gson.toJson(userProfiles);
}
Webservice
This is the webservice I am calling from browser its working fine. But when I call from Android then I get a 500 internal server error. But in server logs I see no error.
What is going wrong?

Whenever an HTTP code starts with a 5 (5xx), it means something got wrong on the server. It is not about your code here, on the android client side, but in the server side implementation.
This is webservice I am calling from broweser its woriking fine ....But when I am calling from android then 500 internal server error
This may mean the the request payload that you are sending from your android app, must be different to that when you do it from your browser. Please print your request payload and double-check everything. Additionally, it might help you also give the request headers a look.

It is hard to give an answer, but i think the session is null when you call the WS using Android. While if you call the WS using a browser the session could be mantained using cookie or sessionId i dont find any line of code that handles cookies or sessionId in some way.
IMO you shouldnt rely on session information.
Hope it helps you.

I recommend using retrofit instead of AsyncTask. It will solve the problem with a cookie.

Related

Alternate for HttpClient in android?

My requirement is to upload the images to server using a Multipart request. I was able to create a Multipart Http Request using the HttpClient, which is deprecated. Is it possible to achieve the same using HttpUrlConnection? If yes, how?
Update:
Current code
{
ProgressDialog progress_dialog;
#Override
protected void onPreExecute() {
// setting progress bar to zero
progress_dialog=new ProgressDialog(CreateAlbum.this);
progress_dialog.setTitle("Loading..");
progress_dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.42:8080/test/fileUpload.php");
try
{
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File sourceFile = new File(fileUri);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
Log.i("RAE", "STATUS CODE IS"+statusCode);
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e("RAE", "Response from server: " + result);
progress_dialog.dismiss();
// showing the server response in an alert dialog
Toast.makeText(getApplicationContext(), "File Uploaded", Toast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
}
AndroidHttpClient has been depreciated and has no longer support from the developers. So one will have to use java's own HttpURLConnection under java.net package. Here is a demo android application which implements HttpURLConnection. Just use the following git commands and run the application in android studio
Clone the git project :-
git clone https://github.com/viper-pranish/android-tutorial.git
Download the right version of project where HttpURLConnection is implemented
git checkout 399e3d1f9624353e522faf350f38a12db635c09a
EDIT
After you understand from my code how to make a POST with HttpUrlConnection, you can edit it and integrate the following answers: Sending files using POST with HttpURLConnection
This is how I make a form-encoded POST:
// Connection
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
conn.setDoInput(true);
// Data to be sent
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(printParams(params));
out.flush();
out.close();
// Print received response
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
where printParams is a simple function to trasform a Map into a string like a=b&c=d:
public static String printParams(Map<String, String> params) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> e: params.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(e.getKey()).append('=').append(e.getValue());
}
return sb.toString();
}
This link has everything you need to send a file to server using multipart. It has been updated to use the most recent http classes in android. I have tested it and use it myself today. Cheers!
http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
For the nexts post show your code, the programmers need see that for give more great help, thanks. On the one hand I always use in my apps httpClient and it's the best way for me because you can configuration a specific client with handling cookies, authentication, connection management, and other features, it's simple if you have the code. If you want to see more info from this theme you can visit this links, in Class Overview part:
http://developer.android.com/reference/org/apache/http/client/HttpClient.html
http://developer.android.com/reference/java/net/HttpURLConnection.html
On the other hand, if you want to do a multiple connections with your server I recommend a parallel programming with httpClient with processes and threads can read more info here: http://developer.android.com/guide/components/processes-and-threads.html
// Last Update //
Sorry Rahul Batra I work with API 21... I noted this for next version of my app. But as the first Step I will try to use a backgroud tasks with httpURLConnection.
This post have a really great information:
http://android-developers.blogspot.com.es/2011/09/androids-http-clients.html
I hope it help you this answer!! If you need more information or anything let me know, good luck Rahul Batra.

POST request from within Android app returns a Connection refused, but it works form the browser

From within my Android app I'm trying to make a POST request to an API which I built using Flask. The API works using the following message from the Postman REST-Client:
POST /api/message/1 HTTP/1.1
Host: 10.0.0.10:5000
Content-Type: application/json
Accept-Encoding: application/json
Cache-Control: no-cache
{"text": "This is a message"}
This works correctly and returns {"testkey": "testmessage"} just as expected. I now make a call from within my Android app using the following AsyncTask:
private class SendMessageTask extends AsyncTask<String, Integer, Boolean> {
protected Boolean doInBackground(String... messages) {
HttpPost post = new HttpPost("http://10.0.0.10/api/message/1");
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept-Encoding", "application/json");
HttpClient client = new DefaultHttpClient();
JSONObject json = new JSONObject();
try {
json.put("text", messages);
} catch (JSONException e) {
e.printStackTrace();
return false;
}
try {
post.setEntity(new StringEntity(json.toString()));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
try {
client.execute(post);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
I simply call this using new SendMessageTask().execute(message.text);.
This however, gives an error saying org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.0.10:5000 refused.
When I simply type in the same url in the browser of my phone I get the expected response (I know that's a GET, but I don't even check for GET or POST on the API side yet).
Does anybody know what I'm doing wrong here? All tips are welcome!
<uses-permission android:name="android.permission.INTERNET"/> add this tag into AndroidManifest.xml of your Android project.

servlet response to android device

I am in a ditch since last few days trying out to get this,but not able to bring out any desired results.I will try to make myself clear that what i am looking for in following points:
I am working on android app,that will update the location of the user on the server using servlets(on my localhost).There is no problem regarding this,all is working fine.
The real problem that came in my way was when i was trying to get response from server back to android device,i just want to return a simple string,or something like that,Most likely a parameter,that will be utilized by the android app.Then i came to know about the json thing that i have to use it for doing what i am looking for.I have searched a lot about it,found some code too,but not able to use it well,
So my questions are
Is it possible to retrieve response from the servlet,and extract the required values from it without using json or any parsing technique,because i needed something like a single string only.
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet();
URI address=new URI("http://xxx.xxx.xxx.xxx:8080/MyServlet");
request.setUri(address);
HttpResponse response=client.execute(request);
The code from the android device requesting the response and the servlet are shown above,however when i call the toString method on response.toString() in android device,it yield me a string with some sequence of numbers,which are of no use to me.
HELP! HELP! HELP!
A simple example of it might help me up,
You could use a servlet that generates plain text result without any encoding technique.
On the server side, just replace your doGet function to look like that:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
On the client side, you could use the following code:
try {
final HttpClient httpClient = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet("http://SERVLET_URL/");
HttpResponse response = httpClient.execute(httpGet);
final HttpEntity entity = response.getEntity();
Log.i(TAG, "Servlet Result: " + EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
Log.e(TAG, "ClientProtocolException", e);
} catch (ParseException e) {
Log.e(TAG, "ParseException", e);
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}

code 401, login required, while using YouTube Data API V3 on Android

I am trying to use the new Youtube Data API on Android to retrieve the Video title from a given ID,
https://www.googleapis.com/youtube/v3/videos?id=6DbS1VB8HGo&part=player&key=XXX
However I keep getting getting a response saying that login required and error code 401.
Am guessing that it has something to do with the authorization token, but I don't understand why I should need this since I am not performing any account specific operations such as updating or deleting from a playlist. All I want is the title and maybe the number of view.
Any help should be appreciated, below is the code I am using:
public class NetTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient();
//param[0]= "https://www.googleapis.com/youtube/v3/videos?id=6DbS1VB8HGo&part=player&key=xxyy"
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpPost);
String responseString = EntityUtils.toString(response.getEntity());
JSONObject responseJSON = new JSONObject(responseString);
responseJSON.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
API documentation says:
Prerequisites
Register your application with Google so that it can submit API requests.

Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized

Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized
I have taken reference from this link
Authentication Error when using HttpPost with DefaultHttpClient on Android
I am working on android app in that backed in Drupal. In that I am sending data from android app to drupal website - webservice in JSON format. Now I can read JSON data from Drupal webservice and writing it in my android application. But facing problem in writing on drupal from android, it generates response with status code
401 Unauthorized
From android native app it generates 401 , while from phonegap-from android when I initiate AJAX request it works perfectly & writes an article or page on drupal website. so that means webservice work perfectly &
my phonegap android app works perfectly there is problem with Android native JAVA application
I am running my android application on Android2.3.4 -> Samsung Galaxy
S Plus - Samsung GT-I9001
here is my code for java android.
==============================
String url = "XXX";
strResponse1 = makeWebForPostIdea(url,title,body);
public static String makeWebForPostIdea(String url, String title,String body)
{
JSONStringer jsonobject = null;
JSONObject json = null;
JSONObject jsonnode = null;
DefaultHttpClient client = new DefaultHttpClient();
Credentials creds = new UsernamePasswordCredentials("username", "password");
client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
HttpPost post = new HttpPost(url);
System.out.println("value of the post =============> "+post);
try {
JSONObject jsonvalue = new JSONObject();
jsonvalue.put("value", body.toString());
JSONArray array = new JSONArray();
array.put(jsonvalue);
jsonnode = new JSONObject();
jsonnode.put("und", array);
System.out.println("######2 jsonnode=======>"+jsonnode.toString());
} catch (JSONException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
try {
jsonobject = new JSONStringer().array().object().key("und").object().key("0").object().key("value").value(body).endObject().endObject().endObject().endArray();
System.out.println("=============>"+jsonobject);
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type","page"));
params.add(new BasicNameValuePair("title",title));
params.add(new BasicNameValuePair("language","und"));
params.add(new BasicNameValuePair("body",jsonobject.toString()));
System.out.println("value of the params =============> "+params);
UrlEncodedFormEntity formEntity = null;
try {
formEntity = new UrlEncodedFormEntity(params);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
post.setEntity(formEntity);
try {
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("=========> statusCode post idea=====> "+statusCode);
if (statusCode == HttpStatus.SC_OK)
{
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
return iStream_to_String(is);
}
else
{
return "Hello This is status ==> :"+String.valueOf(statusCode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String iStream_to_String(InputStream is1) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}
}
}
here is the logcat that I am getting.
08-09 12:41:29.063: I/System.out(336): value of the post =============> org.apache.http.client.methods.HttpPost#4053c3c8
08-09 12:41:29.093: I/System.out(336): ######2 jsonnode=======>{"und": [{"value":"ddddddd"}]}
08-09 12:41:29.093: I/System.out(336): =============>[{"und":{"0":{"value":"ddddddd"}}}]
08-09 12:41:29.103: I/System.out(336): value of the params =============> [type=page, title=hhhh, language=und, body=[{"und":{"0":{"value":"ddddddd"}}}]]
08-09 12:41:30.913: W/DefaultRequestDirector(336): Authentication error: Unable to respond to any of these challenges: {}
08-09 12:41:30.913: I/System.out(336): =========> statusCode post idea=====> 401
08-09 12:41:30.924: I/System.out(336): =========> Response from post idea => Hello This is status ==> :401
Here is my PhoneGap Ajax request it works perfectly.
$('#page_node_create_submit').live('click',function(){
var title = $('#page_node_title').val();
//if (!title) { alert('Please enter a title.'); return false; }
var body = $('#page_node_body').val();
//if (!body) { alert('Please enter a body.'); return false; }
// BEGIN: drupal services node create login (warning: don't use https if you don't have ssl setup)
$.ajax({
url: "XXX",
type: 'post',
data: 'node[type]=page&node[title]=' + encodeURIComponent(title) + '&node[language]=und&node[body][und][0][value]=' + encodeURIComponent(body),
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('page_node_create_submit - failed to login');
console.log(JSON.stringify(XMLHttpRequest));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
$.mobile.changePage("index.html", "slideup");
}
});
// END: drupal services node create
return false;
});
=================================================================================
Edit :
I have tried various methods for Apache httpclient for my error.During this time I have done some research and searched on google and found out some interesting stuff.
1st thing that I found it that Android-Google Officially does not recommend Apache HttpClient that I am using in my code. Check this link. In that Link message from Jesse Wilson from the Dalvik team. In that they suggest to use HttpURLConnection instead of DefaultHttpClient and also written that Android team will no longer develop Apache httpclient . so its the older version that I am using.
http://android-developers.blogspot.in/2011/09/androids-http-clients.html
2nd thing that I have found form this link. It suggests that Android is shipping with Apache's HttpClient 4.0 Beta2, which has a pitfall, when it comes to Basic Authentication. The Authentication method that I am using is of HttpClient 3.x , that I have found out from this link.
check the link.
http://hc.apache.org/httpclient-3.x/authentication.html#Preemptive_Authentication
So the version issue.
http://dlinsin.blogspot.in/2009/08/http-basic-authentication-with-android.html
I have also found some links with potential solution of this problem.
http://ogrelab.ikratko.com/using-newer-version-of-httpclient-like-4-1-x/
Apache HttpClient 4.1 on Android
What version of Apache HTTP Client is bundled in Android 1.6?
From these links , I made a conclusion that if we upgrade the Apache HttpClient to latest stable version , then this problem can be solved.
But this is directly no possible , as Android Team has officially stopped the support for the Apache httpclient.
With this link It could be possible to solve. I have not tried it but I am working on it.
It is the library that can help in upgrading httpclient version in Android.
http://code.google.com/p/httpclientandroidlib/
The other solution could be using HttpURLConnection .I am also working on it.
But most people here on stackoverflow and Internet seems to using DefaultHttpCLient with Android. And ofcourse it is also working with me throughout my application including login,registration,reading from server and session and other functionality.Just it is not working with directly post some article to my server-Drupal website.
It works perfectly with POST request during registration of user on server.
So friends , any suggestions regarding this ? why it is not working just with posting article ?
How come it works from the PhoneGap but not Java. PhoneGap runs the app in a web container and so already has been authenticated - and you have all the right cookies. AJAX will share the same session that and everything 'just works'.
However HTTPClient is a completely different - you are initiating a brand new HTTP session and everything has to be right.
A few comments on how HTTP Auth works:
There are several HTTP authentication methods - and it's the web server that chooses which. Before going any further, check your Drupal configuration to work out whether it is:
Basic Auth (username and password). Everyone and their dog supports this, but it's very insecure. See http://en.wikipedia.org/wiki/Basic_access_authentication for more details
Digest (username and challenge/response hash with MD5. This is more secure but much more complex. Note that MD5 is generally considered weak now. Many libraries support it, including Apache. See http://en.wikipedia.org/wiki/Digest_access_authentication for more details
NTLM (a variant of Kerberos/SPEGNO) which is implemented on IIS. This is not generally supported from Java, although HTTPClient does profess to - but using a different Credentials object. See http://hc.apache.org/httpclient-3.x/authentication.html#NTLM
(Note also that the web container has the 'smarts' to be able to try different authentication methods as requested by the server, all behind the scenes)
Also check the Drupal web logs. A few pointers:
Did you see the HTTPClient connect at all. And is the URL going to the correct resource. Always worth checking from the server's perspective...
Did it go to the right server? One example of what could go wrong: Are you using IP
addresses in the URL against a multi-homed web server, so the request goes to the wrong server?
Check that the authentication sent by the client pre-emptively is the correct type (basic, digest, NTLM)
Let me know if this helps. If not, and you can give more details as per this post, I can follow up with more advice.
You might try to check: How to do http post using apache httpclient with web authentication?
It uses a HttpInterceptor to inject the authentication data, when required
I'd suggest to test first the PHP side out the app. There are several ways to make your own calls including headers and auth. From curl to GraphicalHttpClient (http://itunes.apple.com/us/app/graphicalhttpclient/id433095876?mt=12 , I personally use that and it works decently). There some other options like REST client debugger (https://addons.mozilla.org/en-US/firefox/addon/restclient/)
This way you'll be able to test your call in so many ways which is pain doing directly in the client (sometimes it's just changing from http to https or adding the type of your token in the Authorization header and that's much easier to be madeo n the fly).
Once everything works as expected, reproduce the same call, headers and body in your client and you are ready to go.
I was running into the same "DefaultRequestDirector: Authentication error: Unable to respond to any of these challenges: {}" problem with Drupal services using the loopj android-async-http library (highly recommend it).
The key to the solution for me was in Jose L Ugia's comment in one of the answers regarding paying special attention to the JSON output from Drupal. I was trying to catch a JSONObject but the real message was in array format "["Wrong username or password."]". Switching to JSONArray caught the error properly and allowed me to handle it. In your case I believe it is because you are not posting the login credentials as drupal services expects it.
You should remember with Drupal Services you should do system/connect and grab the session, followed by user/login (and the user/password passed in as parameters) and grab the session and then all your subsequent requests should work. This is why I like using the loopj library because it makes all these requests more manageable. Here is a very basic example of connecting to drupal with loopj. All subsequent posts are easily done using the params.
public class Loopj {
private static final String TAG = "loopj";
private static AsyncHttpClient client = new AsyncHttpClient();
private final PersistentCookieStore myCookieStore;
public Loopj(Context context) {
myCookieStore = new PersistentCookieStore(context);
client.setCookieStore(myCookieStore);
client.addHeader("Content-type", "application/json");
}
public void systemConnect(String uri) throws JSONException {
client.post(uri + "/endpoint/system/connect", new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject json) {
Log.i("TAG", "Connect success =" + json.toString());
}
#Override
public void onFailure(Throwable e, String response) {
Log.e("TAG", "Connect failure");
}
});
}
public void userLogin(String uri) throws JSONException {
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
client.post(uri + "/endpoint/user/login", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray response) {
Log.i("TAG", "Login success =" + response.toString());
}
#Override
public void onFailure(Throwable e, JSONArray json) {
Log.e("TAG", "Login failure");
}
});
}

Categories