Consume Web service using HttpURLConnection
We can call Web services method
in java using classes URL and HttpURLConnection.
And can be used with Android to consume web services
URL: Class URL
represents a Uniform Resource Locator, a
pointer to a "resource" on the World Wide Web. A resource can be
something as simple as a file or a directory, or it can be a reference to a
more complicated object, such as a query to a database or to a search engine.
HttpURLConnection: The
abstract class URLConnection is the superclass of all classes that represent a
communications link between the application and a URL. Instances of this class
can be used both to read from and to write to the resource referenced by the
URL. In general, creating a connection to a URL is a multistep process:
Method name:
openConnection():Manipulate parameters that
affect the connection to the remote resource.
import
java.io.BufferedReader;
import
java.io.DataOutputStream;
import java.io.IOException;
import
java.io.InputStreamReader;
import
java.net.HttpURLConnection;
import java.net.URL;
import
javax.net.ssl.HttpsURLConnection;
import
org.json.JSONException;
import org.json.JSONObject;
public class HttpServiceHandler {
URL url;
HttpURLConnection connection;
DataOutputStream dataOutputStrea;
public static void main(String[] args) {
String
path = "http://localhost:90/testmethod/postdata";
String
method = "POST";
try {
HttpServiceHandler serviceHandler= new HttpServiceHandler(path, method);
serviceHandler.setParameter(serviceHandler.getJson());
System.out.println(serviceHandler.getResponse());
}
catch (Exception e) {
e.printStackTrace();
}
}
public
HttpServiceHandler(String requestUrl, String methodType) throws IOException{
url = new URL(requestUrl);
connection =
(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod(methodType);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.setUseCaches (false);
dataOutputStrea = new DataOutputStream(connection.getOutputStream ());
}
public void
setParameter(JSONObject queryParameter) throws IOException{
dataOutputStrea.writeBytes(queryParameter.toString());
dataOutputStrea.flush();
dataOutputStrea.close();
}
public String getResponse()
throws IOException {
StringBuilder
response = new StringBuilder();
int responseCode = connection.getResponseCode();
if (responseCode ==
HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
response.append(line);
}
}
else {
response.append("");
}
return response.toString();
}
private JSONObject getJson()
throws JSONException{
JSONObject
jsonParam = new JSONObject();
jsonParam.put("Username", "user1");
jsonParam.put("Pasword", "123456");
return jsonParam;
}
}