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.
Related
I followed this article to build my own RESTful API server before. Now, I would like to send a POST request to my API server in android studio. I followed this reply, but it is not successful.
Here is part of my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_create);
ActionBar actionBar = this.getSupportActionBar();
actionBar.setTitle("Test");
actionBar.setDisplayHomeAsUpEnabled(true);
URL url;
HttpURLConnection connection = null;
try {
url = new URL("http://myip/task_manager/v1/register");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
connection.connect();
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream ());
wr.writeBytes("Parameter String"); // I dunno how to write this string..
wr.flush();
wr.close ();
InputStream is;
int response = connection.getResponseCode();
if (response >= 200 && response <=399){
//return is = connection.getInputStream();
//return true;
} else {
//return is = connection.getErrorStream();
//return false;
}
} catch (Exception e) {
e.printStackTrace();
//return false;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
Here is my questions:
1. When "connection.connect();" is run, there is error in console. Is my url string is wrong?
2. What should the "Parameter String" be like? (my parameters are email=xxx, name=yyy)
3. Is there any better method to send a POST request?
Thanks a lot!!!!!!~
to answer your question #3 would suggest using a library like OkHTTP to make that post request. That will make your code way simpler and easier to debug.
Make sure you have the following permissions on your Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Add the library to your gradle file:
compile 'com.squareup.okhttp3:okhttp:3.10.0'
Then, change your onCreate method to the following:
private final OkHttpClient client = new OkHttpClient();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_create);
ActionBar actionBar = this.getSupportActionBar();
actionBar.setTitle("Test");
actionBar.setDisplayHomeAsUpEnabled(true);
makePost();
}
private void makePost(){
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("email", "your-email#email.com")
.addFormDataPart("name", "your-name")
.build();
request = new Request.Builder()
.url("http://myip/task_manager/v1/register")
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
}
And this should make a post request to your endpoint.
If you wanna log it, you can just add a logging interceptor to it.
Hope this helps you out!
Please use volley or retrofit dependency for api calls in android as it is easy to use
Volley Tutorial:
https://www.androidtutorialpoint.com/networking/android-volley-tutorial/
Retrofit Tutorial:
https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
Please refer these two
We (Panos and Rainer - see the comments down) have a server and several Android devices.
We want to send push notifications from our server via GCM to the Android devices.
Now we make a post request to the GCM server. The GCM server response is that all is fine (success==1 and even the message-id)!
BUT the push notification(s) are never delivered to the devices.
If we use the same data and the Chrome addon Postman - the notifications are delivered immediately.
We tried all lot of different solutions. We get always the feedback of the GCM server that all is ok - but the push notifications aren't send.
We also tried this one:
https://github.com/googlesamples/google-services/blob/master/android/gcm/gcmsender/src/main/java/gcm/play/android/samples/com/gcmsender/GcmSender.java
You might also post the URL you use. There is a new GCM enpoint which looks like the following:
https://gcm-http.googleapis.com/gcm/send
I am not yet sure what's causing the issues on your side. But the following is tested and working:
public class Main {
public static void main(String[] args) {
// write your code here
try {
String url = "https://gcm-http.googleapis.com/gcm/send";
URL obj = new URL(url);
HttpsURLConnectionImpl conn = (HttpsURLConnectionImpl) obj.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty ("Authorization", "key=***");
String title = "Short title";
String body = "A body :D";
String token = "****";
String data = "{ \"notification\": { \"title\": \"" + title +"\", \"body\": \"" + body + "\" }, \"to\" : \"" + token + "\", \"priority\" : \"high\" }";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.close();
String text = getText(new InputStreamReader(conn.getInputStream()));
System.out.println(text);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getText(InputStreamReader in) throws IOException {
StringBuilder sb=new StringBuilder();
BufferedReader br = new BufferedReader(in);
String read;
while((read=br.readLine()) != null) {
sb.append(read);
}
br.close();
return sb.toString();
}
}
This is the data used for the Postman request which is working without any problem.
Rainer already mentioned that we tried several implementations on the Java side and it seems that we are always able to communicate with the service and receive a response which seems to look correct so far:
{
"multicast_id":7456542468425129822,
"success":1,
"failure":0,
"canonical_ids":0,
"results":
[{
"message_id":"0:1457548597263237%39c590d7f9fd7ecd"
}]
}
Not sure if I'm on the right track but do you mean downstream HTTP messages (plain text)?
Tried to send the following JSON to the service (from Postman) which results again in a positive response but this time the notification did not reach the device (just to make that clear, at the moment there is no app on the device listening actively for incoming notifications -> first of all we just want to ensure that they generally arrive on the device):
{
"data":
{
"score": "5x1",
"time": "15:10"
},
"to" : "SECRET-DEVICE-TOKEN"
}
Thanks to all of you trying to help here but to be honest, this issue is really frustrating. Communicating with an interface\service which seems not to be able to return a useful response in case the request contains maybe evil stuff which will finally prevent GCM from sending the push notification to the device, feels like a pain in the ass. If Postman would also fail I would say ok, you can not be so stupid :-)
Here are some quick'n dirty implementations we have already used.
Example
try
{
URL url = new URL(apiUrl);
HttpsURLConnection conn = (HttpsURLConnection);//also tried HttpURLConnection
url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);
conn.setDoOutput(true);
String json = "{\"priority\":\"high\",\"notification\":{\"title\":\"Some title\",\"text\":\"Some text\"},\"to\":\""+deviceToken+"\"}";
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
}
catch(Exception exc)
{
System.out.println("Error while trying to send push notification: "+exc);
}
Example
HttpClient httpClient = HttpClientBuilder.create().build();
try
{
HttpPost request = new HttpPost(apiUrl);
StringEntity params =new StringEntity("{\"priority\":\"high\",\"notification\":{\title\":\"Some title\",\"text\":\"Some text\"},\"to\":\""+deviceToken+"\"}");
request.addHeader("Content-Type", "application/json");
request.addHeader("Authorization", "key="+apiKey);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// check response
System.out.println(response.getStatusLine().toString());
}catch (Exception exc) {
System.out.println("Error while trying to send push notification: "+exc);
} finally {
httpClient.getConnectionManager().shutdown(); //Deprecated
}
Example
try
{
String charset = "UTF-8";
URLConnection connection = new URL(apiUrl).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
connection.setRequestProperty("Authorization", "key="+apiKey);
String param = "{\"priority\":\"high\",\"notification\":{\"title\":\"Some title\",\"text\":\"Some text\"},\"to\":\""+deviceToken+"\"}";
try (OutputStream output = connection.getOutputStream())
{
output.write(param.getBytes(charset));
}
InputStream response = connection.getInputStream();
}
catch(Exception exc)
{
System.out.println("Error while trying to send push notification: "+exc);
}
Example
try
{
// prepare JSON
JSONObject jGcmData = new JSONObject();
JSONObject jData = new JSONObject();
jData.put("message", "{ \"data\": {\"score\": \"5x1\",\"time\": \"15:10\"},\"to\" : \""+deviceToken+"\"}");
jGcmData.put("to", deviceToken);
jGcmData.put("data", jData);
// Create connection to send GCM Message request.
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// Send GCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jGcmData.toString().getBytes());
// Read GCM response.
InputStream inputStream = conn.getInputStream();
String resp = IOUtils.toString(inputStream);
System.out.println(resp);
} catch (IOException e) {
System.out.println("Unable to send GCM message. "+e);
}
Mike, with your example it's working also on our side. After comparing your implementation with the on eon our side, the only real difference I found is the used URL!!
Somehow the URL used in our Java implementation was https://android.googleapis.com/gcm/send
Seems that https://gcm-http.googleapis.com/gcm/send is the right one which by the way was also used for our Postman tests.
But why on hell is the URL from our failed tests still somehowe valid and returns a response!?
Setting the priority to high in the json resolved the issue for me.
'registration_ids' => $id,
'priority' => 'high',
'data' => $load
For our case, the clients Android devices had intermittent internet connection issue, that is, network dropouts thus causing notification delivery failed. We resolved the reliability issue with the following JAVA GCM code:
gcmPayload.setTime_to_live(messageExpiryTime); //in seconds. Set notification message expiry to give user time to receive it in case they have intermittent internet connection, or phone was off
gcmPayload.setPriority("high");
and APNS code:
ApnsService apnsService = APNS.newService().withCert(certificateStream, configurations.getApnPassword()).withProductionDestination().build();
PayloadBuilder payloadBuilder = APNS.newPayload();
...
payloadBuilder.instantDeliveryOrSilentNotification(); //same as content-available=true
String payload = payloadBuilder.build();
Integer now = (int)(new Date().getTime()/1000);
//use EnhancedApnsNotification to set message expiry time
for(String deviceToken : deviceTokens) {
EnhancedApnsNotification notification = new EnhancedApnsNotification(EnhancedApnsNotification.INCREMENT_ID() /* Next ID */,
now + messageExpiryTime /* Expiry time in seconds */,
deviceToken /* Device Token */,
payload);
apnsService.push(notification);
}
Also, remember to consider time zone if your backend server time is different to the client mobile app time.
Currently I'm using HttpClient, HttpPost to send data to my PHP server from an Android app but all those methods were deprecated in API 22 and removed in API 23, so what are the alternative options to it?
I searched everywhere but I didn't find anything.
I've also encountered with this problem to solve that I've made my own class.
Which based on java.net, and supports up to android's API 24
please check it out:
HttpRequest.java
Using this class you can easily:
Send Http GET request
Send Http POST request
Send Http PUT request
Send Http DELETE
Send request without extra data params & check response HTTP status code
Add custom HTTP Headers to request (using varargs)
Add data params as String query to request
Add data params as HashMap {key=value}
Accept Response as String
Accept Response as JSONObject
Accept response as byte [] Array of bytes (useful for files)
and any combination of those - just with one single line of code)
Here are a few examples:
//Consider next request:
HttpRequest req=new HttpRequest("http://host:port/path");
Example 1:
//prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked
req.prepare(HttpRequest.Method.POST).withData("name=Bubu&age=29").send();
Example 2:
// prepare http get request, send to "http://host:port/path" and read server's response as String
req.prepare().sendAndReadString();
Example 3:
// prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29 and read server's response as JSONObject
HashMap<String, String>params=new HashMap<>();
params.put("name", "Groot");
params.put("age", "29");
req.prepare(HttpRequest.Method.POST).withData(params).sendAndReadJSON();
Example 4:
//send Http Post request to "http://url.com/b.c" in background using AsyncTask
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
try {
response=new HttpRequest("http://url.com/b.c").prepare(HttpRequest.Method.POST).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
}
}.execute();
Example 5:
//Send Http PUT request to: "http://some.url" with request header:
String json="{\"name\":\"Deadpool\",\"age\":40}";//JSON that we need to send
String url="http://some.url";//URL address where we need to send it
HttpRequest req=new HttpRequest(url);//HttpRequest to url: "http://some.url"
req.withHeaders("Content-Type: application/json");//add request header: "Content-Type: application/json"
req.prepare(HttpRequest.Method.PUT);//Set HttpRequest method as PUT
req.withData(json);//Add json data to request body
JSONObject res=req.sendAndReadJSON();//Accept response as JSONObject
Example 6:
//Equivalent to previous example, but in a shorter way (using methods chaining):
String json="{\"name\":\"Deadpool\",\"age\":40}";//JSON that we need to send
String url="http://some.url";//URL address where we need to send it
//Shortcut for example 5 complex request sending & reading response in one (chained) line
JSONObject res=new HttpRequest(url).withHeaders("Content-Type: application/json").prepare(HttpRequest.Method.PUT).withData(json).sendAndReadJSON();
Example 7:
//Downloading file
byte [] file = new HttpRequest("http://some.file.url").prepare().sendAndReadBytes();
FileOutputStream fos = new FileOutputStream("smile.png");
fos.write(file);
fos.close();
The HttpClient was deprecated and now removed:
org.apache.http.client.HttpClient:
This interface was deprecated in API level 22.
Please use openConnection() instead. Please visit this webpage for further details.
means that you should switch to java.net.URL.openConnection().
See also the new HttpURLConnection documentation.
Here's how you could do it:
URL url = new URL("http://some-server");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
IOUtils documentation: Apache Commons IO
IOUtils Maven dependency: http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar
The following code is in an AsyncTask:
In my background process:
String POST_PARAMS = "param1=" + params[0] + "¶m2=" + params[1];
URL obj = null;
HttpURLConnection con = null;
try {
obj = new URL(Config.YOUR_SERVER_URL);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// For POST only - BEGIN
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
Log.i(TAG, "POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Log.i(TAG, response.toString());
} else {
Log.i(TAG, "POST request did not work.");
}
} catch (IOException e) {
e.printStackTrace();
}
Reference:
http://www.journaldev.com/7148/java-httpurlconnection-example-to-send-http-getpost-requests
This is the solution that I have applied to the problem that httpclient deprecated in this version of android 22`
public static final String USER_AGENT = "Mozilla/5.0";
public static String sendPost(String _url,Map<String,String> parameter) {
StringBuilder params=new StringBuilder("");
String result="";
try {
for(String s:parameter.keySet()){
params.append("&"+s+"=");
params.append(URLEncoder.encode(parameter.get(s),"UTF-8"));
}
String url =_url;
URL obj = new URL(_url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "UTF-8");
con.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream());
outputStreamWriter.write(params.toString());
outputStreamWriter.flush();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine + "\n");
}
in.close();
result = response.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}finally {
return result;
}
}
You are free to continue using HttpClient. Google deprecated only their own version of Apache's components. You can install fresh, powerful and non deprecated version of Apache's HttpClient like I described in this post: https://stackoverflow.com/a/37623038/1727132
if targeted for API 22 and older, then should add the following line into build.gradle
dependencies {
compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}
if targeted for API 23 and later, then should add the following line into build.gradle
dependencies {
compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'
}
If still want to use httpclient library, in Android Marshmallow (sdk 23), you can add:
useLibrary 'org.apache.http.legacy'
to build.gradle in the android {} section as a workaround. This seems to be necessary for some of Google's own gms libraries!
Which client is best?
Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best
choice for these releases.
For Gingerbread and better, HttpURLConnection is the best choice. Its
simple API and small size makes it great fit for Android...
Reference here for more info (Android developers blog)
You can use my easy to use custom class.
Just create an object of the abstract class(Anonymous) and define onsuccess() and onfail() method.
https://github.com/creativo123/POSTConnection
i had similar issues in using HttpClent and HttpPost method since i didn't wanted change my code so i found alternate option in build.gradle(module) file by removing 'rc3' from buildToolsVersion "23.0.1 rc3" and it worked for me. Hope that Helps.
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.
I having an issue from my HTTP Post.
The code I'm using are working (have tested to post data to a guestbook form and it worked).
Now what I want. I have created two EditText forms, that holds values. I have a submit button there I post this data (like the test I wrote about before), but now I want to post it into a login.php page (that in a normal browser redirects me to the member.php page).
Although I know the forms are correctly filled in and it successfully posted on the "test" site, I wanna get the response from login.php and check if the user is successfully logged in or if it failed, if succeeded -> redirect me to member.php page.
All I know is this:
HttpResponse response = httpclient.execute(httppost);
that executes the command. But how should I achieve the login check? Any further use of the response variable?
Well... your approach is not good at all. If you are going to allow user authenticate through your app, why do you want to redirect the user to a member.php page? why don't you just put the login form in a login.php file on the server and make the user browse through your site?
As user, if an app allows me to authenticate using EditTexts inside UI, I would expect to access all the content through the app instead of being redirected to a web interface.
Anyway, if you decide to continue doing it that way keep in mind that you would have to parse and process cookies manually, and inject them into the WebView (Google about the CookieManager class). That's the way how the user will really be logged-in in your web app.
Can you provide a small example of how to set it up? The stream I will get, is that a special server response for example, a successfully login?
Here you have:
public String getPostRequest(String url, String user, String pass) {
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = postClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result; // here is a string of the result!!!
}
}
} catch (Exception e) {}
return null; // if it gets here, something wrong happens with the connection
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
How do you use it? Something like this:
String result = getPostRequest("http://yourpage.com/login.php", "the username", "his/her pass");
if( result.equals("OK") ){
// voila!
}
I'm here supposing that you have something like this in your PHP code:
<?php
// login logic here
if( $success ){
die("OK");
}
?>