Android HttpPost: how to get the result
Try to use the EntityUtil
on your response:
String responseBody = EntityUtils.toString(response.getEntity());
How to get response after using POST method in Android
Try using HttpUrlConnection
String Url, query;
InputStream inputStream;
HttpURLConnection urlConnection;
byte[] outputBytes;
String ResponseData;
Context context;
try{
URL url = new URL(Url);
urlConnection = (HttpURLConnection) url.openConnection();
outputBytes = query.getBytes("UTF-8");
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
OutputStream os = urlConnection.getOutputStream();
os.write(outputBytes);
os.flush();
os.close();
inputStream = new BufferedInputStream(urlConnection.getInputStream());
ResponseData = convertStreamToString(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public 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();
}
Http post get response Android
You can use a function like that, and convert the String returned in JSONObject or whatever. Adapt it to your code if you need it, but I think it's "almost" a generic solution.
private String callServer(List<BasicNameValuePair> nameValuePairs,String path) {
InputStream is = null;
StringBuilder sb = null;
String result = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(path);
//Your headers here
//I'm afraid there are too much headers. Try cleaning and choosing only the neccessary ones.
httppost.setHeader("Connection", "keep-alive");
httppost.setHeader("Content-Length", "172");
httppost.setHeader("X-GWT-Module-Base", "http://portus.puertos.es/Portus_RT/portusgwt/");
httppost.setHeader("X-GWT-Permutation", "3DEDE3A69CBBE62D4C3F58BF7278538F");
httppost.setHeader("Origin", "http://portus.puertos.es");
httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36");
httppost.setHeader("Accept", "*/*");
httppost.setHeader("Referer", "http://portus.puertos.es/Portus_RT/?locale=es");
httppost.setHeader("Accept-Encoding", "gzip,deflate");
httppost.setHeader("Accept-Language", "en-US,en;q=0.8,es;q=0.6,ca;q=0.4");
httppost.setHeader("AlexaToolbar-ALX_NS_PH", "AlexaToolbar/alxg-3.3");
httppost.setHeader("Content-Type", "text/x-gwt-rpc; charset=UTF-8");
httppost.setHeader("Host", "portus.puertos.es");
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e1) {
e1.printStackTrace();
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
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());
}
return result;
}
Even tough, I recommend you to use this component for rest APIs and HTTP Connections:
https://github.com/matessoftwaresolutions/AndroidHttpRestService
Take a look and evaluate if it worths to you. It allows you to manage "no connection", show/hide dialogs before and after the call (or whatever) and some more features.
I hope I would help you. ;)
Android Login with HTTP post, get results
Not the best code refactoring, but just to give you a hint.
I would create an interface (lets call it 'LogInListener'):
public interface LoginListener {
void onSuccessfulLogin(String response);
void onFailedLogin(String response);
}
The 'MainActivity' class would implement that interface and set itself as a listener the 'PostDataAsyncTask'. So, creating the async task from the main activity would look like this:
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
PostDataAsyncTask postTask = new PostDataAsyncTask(this);
postTask.execute(params);
I would move 'PostDataAsyncTask' class into a new file:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
private static final String ERROR_RESPONSE = "notok";
private LoginListener listener = null;
public PostDataAsyncTask(LoginListener listener) {
this.listener = listener;
}
@Override
protected String doInBackground(String... params) {
String postResponse = "";
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
postResponse = EntityUtils.toString(resEntity).trim();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
@Override
protected void onPostExecute(String postResponse) {
if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
listener.onFailedLogin(postResponse);
} else {
listener.onSuccessfulLogin(postResponse);
}
}
}
So, 'doInBackground' returns the response to 'onPostExecute' (which runs on the UI thread), and 'onPostExecute' routes the result (success or failure) to the MainActivity, which implements the 'LogInListener' methods:
@Override
public void onSuccessfulLogin(String response) {
// you have access to the ui thread here - do whatever you want on suscess
// I'm just assuming that you'd like to start that activity
Intent Hotels_btn_pressed = new Intent(this, Hotels.class);
startActivity(Hotels_btn_pressed);
}
@Override
public void onFailedLogin(String response) {
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}
I just assumed that that's what you wanted to do on success: start a new activity, and show a toast on fail.
HttpPost get HTTP response code Android
More of your code would be helpful here but the way I do it is this:
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = client.execute(httppost);
int responseCode = response.getStatusLine().getStatusCode()
How to use HttpPost to get the second response
You can pass your custom ResponseHandler
into execute
method so that you can chain your second request inside it.
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
@Override
public String handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
// The response of first request is available here
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
Reference:
Official Example of ResponseHandler
Doc of Execute function
Apart from that, okhttp / Retrofit
are much popular and powerful HttpClient
in terms of android development. Please feel free to check it out.
OkHttp
Retrofit
How to get result from AsyncTask http post?
Create another method in activity to set the output text and taking an input string parameter as below.
public void setOutputText(String outputText) {
output.setText(outputText);
}
Then call this method in the onPostExecute method of AsyncTask as below.
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
setOutputText(result);
}
Android GET and POST Request
You can use the HttpURLConnection
class (in java.net) to send a POST or GET HTTP request. It is the same as any other application that might want to send an HTTP request. The code to send an Http Request would look like this:
import java.net.*;
import java.io.*;
public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
String post = "this will be the post data that you will send"
request.setDoOutput(true);
request.addRequestProperty("Content-Length", Integer.toString(post.length)); //add the content length of the post data
request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
request.setMethod("POST");
request.connect();
OutputStreamWriter writer = new OutputStreamWriter(request.getOutputStream()); //we will write our request data here
writer.write(post);
writer.flush();
}
}
A GET request will look a little bit different, but much of the code is the same. You don't have to worry about doing output with streams or specifying the content-length or content-type:
import java.net.*;
import java.io.*;
public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
request.setMethod("GET");
request.connect();
}
}
Android, Java: HTTP POST Request
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair
.
An alternative is to use (Http)URLConnection
. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection
javadoc.
Related Topics
How to Solve the "Double-Checked Locking Is Broken" Declaration in Java
Encoding Url Query Parameters in Java
Variable Length (Dynamic) Arrays in Java
How to Make an Array of Arrays in Java
What Is the Use of System.In.Read()
Read the Output from Java Exec
Displaying a Histogram of Image Data
Getting Strange Output When Printing Result of a String Comparison
Jpanel & Components Change Position Automatically
Can Not Find the Tag Library Descriptor for "Http://Java.Sun.Com/Jsp/Jstl/Core"
Using File.Listfiles with Filenameextensionfilter
Custom JSON Deserialization with Jackson
Background Timer Task in Jsp/Servlet Web Application
How to Use an Arraylist as a Prepared Statement Parameter
How to Cast a Double to an Int in Java by Rounding It Down