In Android we can communicate with server
using HTTP request methods for getting some details from the server.We use
RESTful service.Mainly we use two types of HTTP request HTTP GET(),HTTP POST()
methods.
In some case we have to give some values to
the server for fetching some informations, then we use commonly HTTP POST() and
if we simply want to request for some datas we use HTTP GET().
Lets see HTTP POST() method.
public void getResponse(String a, String b) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("URL"); //here write the url
List < NameValuePair > nameValueList = new ArrayList < NameValuePair > (2);
nameValueList.add(new BasicNameValuePair("keyword", a));
nameValueList.add(new BasicNameValuePair("keyword", b));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValueList));
HttpResponse response = httpclient.execute(httppost);
Log.i("Tag", response.getStatusLine().toString());
String responseStr = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
}
}
In the above method
we are passing two string values a and b, using namevaluepair method. Finally
we get the response from the server in responseStr.
HTTP GET() method
public void getResponse() {
URL url;
try {
url = new URL("URL"); //here write the url
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-length", "0");
conn.setAllowUserInteraction(false);
// Starts the query
conn.connect();
int status = conn.getResponseCode();
StringBuilder sb = new StringBuilder();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
String response = sb.toString();
}
} catch (Exception e) {
}
}
Here we are using HTTP GET() method.At first
connection is established.Here I am checking the status line: If the request is
procesed succesfully i am getting status code as 201.Finally We get the
response in the string response;
We can also send values using HTTP
GET()method by appending values with the URL,but commonly we won't use it.HTTP
POST method is considered to be more secure than HTTP GET() method.
Comments
Post a Comment