I have a web server, where i log in in my android Application, after that loging i recive as an XML the user who logged with a field named token.
This token is used to keep open the session during next calls to webService, and it works sendidnt the token as a cookie named "acrsession" but it seems not working because everytime i tried to check if im logged in (using a get call named currentUser) it returns me forbidden, so i think it isnt working good.
Here is my AsyncTask class who do the calls to server.
public String getFileName() {
return FileName;
}
public void setFileName(String fileName) {
FileName = fileName;
}
private String Response;
private URI uriInfo;
private String FileName;
public WebServiceTask(int taskType, Context mContext, String processMessage,String token) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
this.token=token;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
public void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
//hideKeyboard();
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
this.Response=response;
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
int responseCode=0;
// Create a local instance of cookie store
//CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
//HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
//localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//CookieManager cookieManager= CookieManager.getInstance();
this.getLocalContext();
this.cookieStore.addCookie(new BasicClientCookie("acrsession", this.token));
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
// Add parameters
httppost.setEntity(new UrlEncodedFormEntity(params));
int executeCount = 0;
do
{
pDlg.setMessage("Logging in.. ("+(executeCount+1)+"/5)");
// Execute HTTP Post Request
executeCount++;
response = httpclient.execute(httppost,localContext);
responseCode = response.getStatusLine().getStatusCode();
// If you want to see the response code, you can Log it
// out here by calling:
// Log.d("256 Design", "statusCode: " + responseCode)
} while (executeCount < 5 && responseCode == 408);
uriInfo = httppost.getURI();
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
response = httpclient.execute(httpget,localContext);
responseCode = response.getStatusLine().getStatusCode();
httpget.getRequestLine();
uriInfo = httpget.getURI();
break;
case PUT_TASK:
HttpPut httpput = new HttpPut(url);
File file = new File(this.FileName);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httpput.setEntity(reqEntity);
response = httpclient.execute(httpput,localContext);
responseCode = response.getStatusLine().getStatusCode();
httpput.getRequestLine();
uriInfo = httpput.getURI();
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
private String inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
// Read response until the end
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
// Return full string
this.Response=total.toString();
return total.toString();
}
public String getResponse(){
return this.Response;
}
public HttpContext getLocalContext()
{
if (localContext == null)
{
localContext = new BasicHttpContext();
cookieStore = new BasicCookieStore();
localContext.setAttribute(ClientContext.COOKIE_ORIGIN, cookieStore);
localContext.setAttribute(ClientContext.COOKIE_SPEC, cookieStore);
localContext.setAttribute(ClientContext.COOKIESPEC_REGISTRY, cookieStore);
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);// to make sure that cookies provided by the server can be reused
}
return localContext;
}
Plesae tell me what im doing bad.
Thanks in advance.
Well, finally i found the solution, everything was ok but i fortgot to set cookie Domain and path, so onced i putted it it worked.
Now cookie creation looks like this:
this.localContext=this.getLocalContext();
BasicClientCookie cookie = new BasicClientCookie("acrsession", this.token);
cookie.setDomain(this.Domain);
cookie.setPath(this.path);
this.cookieStore.addCookie(cookie);
localContext.setAttribute(ClientContext.COOKIE_STORE, this.cookieStore);
Hope it will help someone else.
Related
I am trying to use this method i also tried to impot libriries but all in vain. Kindly help me. Not any HTTPClient library is showing on my andriod studio. Help would be appreciated
public String getHttpPost(String url,ContentValues) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
Oh!Still you are using HttpClient.You can use HttpURLConnection,Volley etc. HttpClient class is now deprecated.Also add Internet permission, and dependensies in gradle file.
HttpURLConnection urlConnection = null;
try {
URL urlToRequest = new URL(_url);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(30000);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
if (_authenticationKey != null) {
urlConnection.setRequestProperty(_authenticationKey, _authenticationValue);
}
if (_jsonPacket != null) {
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(_jsonPacket);
wr.flush();
}
int statusCode = urlConnection.getResponseCode();
JSONObject job;
if (statusCode != HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getErrorStream());
String responseString = getResponseString(in);
if (isJSONValid(responseString)) {
job = new JSONObject(responseString);
return new PostingResult(job, Constants.IntegerConstants.failureFromWebService, "");
} else {
return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + "Response code = " + statusCode);
}
} else {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String responseString = getResponseString(in);
if (isJSONValid(responseString)) {
job = new JSONObject(responseString);
return new PostingResult(job, Constants.IntegerConstants.success, "");
} else {
return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + Constants.StringConstants.serverReadingResponseFailed);
}
}
You can use "Volley" library to make network call.
eg.
Add this line in build.gradle (Module:app)
compile 'com.mcxiaoke.volley:library:1.0.19'
As you are making network call you need internet permission. So add Internet permission line in Manifest.xml
Now you need to write a small method inside your class where you need to make network call and need to pass Hashmap to it. Hashmap contains all your post parameters.
private void getJSONResponse(HashMap<String, String> map, String url) {
pd.show();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(map), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Mayur", "Response : " + response);
//tv_res.setText(response.toString());
//pd.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error Occured", Toast.LENGTH_SHORT).show();
//tv_res.setText("ERROR");
//pd.dismiss();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(20000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));Volley.newRequestQueue(this).add(request);}
Now in your onCreate method or any other method just create a Hashmap of post parameters and pass it to this method with post url.
eg.
HashMap<String, String> map = new HashMap<String, String>();
map.put("fname", "Mayur");
map.put("lname", "Thakur");
getJSONResponse(map,<your url>);
I know this should have been easy to find online but none of the articles addressed my issue so I am coming to SO for some help.I am trying to make an httppost request in android to a wcf restful web service. I want to create an xml and then I want to post that to the service and get a response from the service.
I have created a WCF Rest service and it has a method to accept the xml and respond back.Here is the code for the method:
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "DoWork1/{xml}",
BodyStyle = WebMessageBodyStyle.Wrapped)]
XElement DoWork1(string xml);
public XElement DoWork1(string xml)
{
StreamReader reader = null;
XDocument xDocRequest = null;
string strXmlRequest = string.Empty;
reader = new StreamReader(xml);
strXmlRequest = reader.ReadToEnd();
xDocRequest = XDocument.Parse(strXmlRequest);
string response = "<Result>OK</Result>";
return XElement.Parse(response);
}
Here is android code to post xml :
String myXML = "<? xml version=1.0> <Request> <Elemtnt> <data id=\"1\">E1203</data> <data id=\"2\">E1204</data> </Element> </Request>";
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("http://192.168.0.15/Httppost/Service1.svc/DoWork1/"+myXML);
This code crasehes throwing an illegal character in the path exception.
How can I make post an xml file to this service from android. Any suggestions would be really appreciated.
public class HTTPPostActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
makePostRequest();
}
private void makePostRequest() {
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("www.example.com");
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", "test_user"));
nameValuePair.add(new BasicNameValuePair("password", "123456789"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
}
}
To connect to WCF service on android you have to use external library like ksoap.
enter link description here
Then you can adapt for your needs this class:
public abstract class SoapWorker extends AsyncTask<SoapWorker.SoapRequest,Void,Object> {
public static class SoapRequest{
private LinkedHashMap<String,Object> params;
private String methodName;
private String namespace;
private String actionName;
private String url;
public SoapRequest(String url, String methodName,String namespace){
this.methodName = methodName;
this.params = new LinkedHashMap<>();
this.namespace=namespace;
this.actionName=this.namespace + "IService/" + methodName;
this.url=url;
}
public void addParam(String key,Object value){
this.params.put(key,value);
}
}
#Override
protected Object doInBackground(SoapRequest input) {
try {
SoapObject request = new SoapObject(input.namespace, input.methodName);
for(Map.Entry<String, Object> entry : input.params.entrySet()){
request.addProperty(entry.getKey(),entry.getValue());
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(input.url);
androidHttpTransport.call(input.actionName, envelope);
input.params.clear();
return parseResponse(envelope.getResponse());
} catch (Exception e) {
Log.e("SoapWorker", "error " + e);
return e;
}
}
#WorkerThread
public abstract Object parseResponse(Object response);
}
Use this class like:
SoapWorker.SoapRequest request = new SoapWorker.SoapRequest(URL,METHOD_NAME,NAMESPACE);
request.addParam(KEY,VALUE);
....
request.addParam(KEY,VALUE);
SoapWorker worker = new SoapWorker(){
#Override
public Object parseResponse(Object response) {
if(response==null)
return null;
//parse response
// this is background thread
return response;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// this is ui thread
//update your ui
}
};
worker.execute(request);
Use this asynck task only in application context.Pass data to Activity / fragment only using EventBus from green roboot or otto.
I want to call a rest webservice with POST method.Below is the service url and its parameters which I need to pass
Rest Service: https://url/SSOServer/SSO.svc/RestService/Login
Json Object {"ProductCode":"AB","DeviceType":"android Simulator","UserName":"","ModuleCode":"AB_MOBILE","DeviceId":"device-id","Version":"1.0.0.19","CustomerCode":"w","Password":""}
Here is my post request code:
public void sendHttpPost() throws ClientProtocolException, IOException{
HttpPost httpPostRequest = new HttpPost(url + buildParams());
// add headers
Iterator it = headers.entrySet().iterator();
Iterator itP = params.entrySet().iterator();
while (it.hasNext()) {
Entry header = (Entry) it.next();
httpPostRequest.addHeader((String)header.getKey(), (String)header.getValue());
}
HttpClient client = new DefaultHttpClient();
HttpResponse resp;
resp = client.execute(httpPostRequest);
this.respCode = resp.getStatusLine().getStatusCode();
Log.i(TAG, "response code: " + getResponseCode());
this.responsePhrase = resp.getStatusLine().getReasonPhrase();
Log.i(TAG, "error msg: " + getErrorMsg());
HttpEntity entity = resp.getEntity();
if (entity != null){
InputStream is = entity.getContent();
//Header contentEncoding = resp.getFirstHeader("Content-encoding");
//Log.i(TAG, "endoding" + contentEncoding.getValue());
response = convertStreamToString(is);
//response = response.substring(1,response.length()-1);
//response = "{" + response + "}";
Log.i(TAG, "response: " + response);
is.close();
}
}
My question is how to add json data to this request??
Use below class
public class RestClient
{
private ArrayList<NameValuePair> params;
private ArrayList<NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse()
{
return response;
}
public String getErrorMessage()
{
return message;
}
public int getResponseCode()
{
return responseCode;
}
public RestClient(String url) {
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch (method)
{
case GET:
{
// add parameters
String combinedParams = "";
if (!params.isEmpty())
{
combinedParams += "";
for (NameValuePair p : params)
{
String paramString = p.getName() + "" + URLEncoder.encode(p.getValue(),"UTF-8");
if (combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
// add headers
for (NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
// add headers
for (NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if (!params.isEmpty())
{
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url) throws Exception
{
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
}
private static 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();
}
public InputStream getInputStream(){
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse;
try
{
HttpPost request = new HttpPost(url);
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
return instream;
/* response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();*/
}
}
catch (ClientProtocolException e)
{
client.getConnectionManager().shutdown();
e.printStackTrace();
}
catch (IOException e)
{
client.getConnectionManager().shutdown();
e.printStackTrace();
}
return null;
}
public enum RequestMethod
{
GET,
POST
}
}
Here is the code how to use above class
RestClient client=new RestClient(Webservices.student_details);
JSONObject obj=new JSONObject();
obj.put("StudentId",preferences.getStudentId());
client.AddParam("",obj.toString());
client.Execute(RequestMethod.GET);
String response=client.getResponse();
Hope this will help you
Q: how to add json data to this request?
A: Set your content type, length and write the payload.
Here's an example:
http://localtone.blogspot.com/2009/07/post-json-using-android-and-httpclient.html
JSONObject holder = new JSONObject();
...
JSONObject data = new JSONObject();
...
// Some example name=value pairs
while(iter.hasNext()) {
Map.Entry pairs = (Map.Entry)iter.next();
String key = (String)pairs.getKey();
Map m = (Map)pairs.getValue();
JSONObject data = new JSONObject();
Iterator iter2 = m.entrySet().iterator();
while(iter2.hasNext()) {
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
holder.put(key, data);
}
...
StringEntity se = new StringEntity(holder.toString());
...
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
...
Can anyone point me to a good implementation of a way to send GET and POST Requests. They are alot of ways to do these, and i am looking for the best implementation. Secondly is there a generic way to send both these methods rather then using two different ways. After all the GET method merely has the params in the Query Strings, whereas the POST method uses the headers for the Params.
Thanks.
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();
}
}
I prefer using dedicated class to do GET/POST and any HTTP connections or requests.
Moreover I use HttpClient to execute these GET/POST methods.
Below is sample from my project. I needed thread-safe execution so there is ThreadSafeClientConnManager.
There is an example of using GET (fetchData) and POST (sendOrder)
As you can see execute is general method for executing HttpUriRequest - it can be POST or GET.
public final class ClientHttpClient {
private static DefaultHttpClient client;
private static CookieStore cookieStore;
private static HttpContext httpContext;
static {
cookieStore = new BasicCookieStore();
httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
client = getThreadSafeClient();
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, AppConstants.CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, AppConstants.SOCKET_TIMEOUT);
client.setParams(params);
}
private static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()),
params);
return client;
}
private ClientHttpClient() {
}
public static String execute(HttpUriRequest http) throws IOException {
BufferedReader reader = null;
try {
StringBuilder builder = new StringBuilder();
HttpResponse response = client.execute(http, httpContext);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
reader = new BufferedReader(new InputStreamReader(content, CHARSET));
String line = null;
while((line = reader.readLine()) != null) {
builder.append(line);
}
if(statusCode != 200) {
throw new IOException("statusCode=" + statusCode + ", " + http.getURI().toASCIIString()
+ ", " + builder.toString());
}
return builder.toString();
}
finally {
if(reader != null) {
reader.close();
}
}
}
public static List<OverlayItem> fetchData(Info info) throws JSONException, IOException {
List<OverlayItem> out = new LinkedList<OverlayItem>();
HttpGet request = buildFetchHttp(info);
String json = execute(request);
if(json.trim().length() <= 2) {
return out;
}
try {
JSONObject responseJSON = new JSONObject(json);
if(responseJSON.has("auth_error")) {
throw new IOException("auth_error");
}
}
catch(JSONException e) {
//ok there was no error, because response is JSONArray - not JSONObject
}
JSONArray jsonArray = new JSONArray(json);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject chunk = jsonArray.getJSONObject(i);
ChunkParser parser = new ChunkParser(chunk);
if(!parser.hasErrors()) {
out.add(parser.parse());
}
}
return out;
}
private static HttpGet buildFetchHttp(Info info) throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder();
builder.append(FETCH_TAXIS_URL);
builder.append("?minLat=" + URLEncoder.encode("" + mapBounds.getMinLatitude(), ENCODING));
builder.append("&maxLat=" + URLEncoder.encode("" + mapBounds.getMaxLatitude(), ENCODING));
builder.append("&minLon=" + URLEncoder.encode("" + mapBounds.getMinLongitude(), ENCODING));
builder.append("&maxLon=" + URLEncoder.encode("" + mapBounds.getMaxLongitude(), ENCODING));
HttpGet get = new HttpGet(builder.toString());
return get;
}
public static int sendOrder(OrderInfo info) throws IOException {
HttpPost post = new HttpPost(SEND_ORDER_URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("id", "" + info.getTaxi().getId()));
nameValuePairs.add(new BasicNameValuePair("address", info.getAddressText()));
nameValuePairs.add(new BasicNameValuePair("name", info.getName()));
nameValuePairs.add(new BasicNameValuePair("surname", info.getSurname()));
nameValuePairs.add(new BasicNameValuePair("phone", info.getPhoneNumber()));
nameValuePairs.add(new BasicNameValuePair("passengers", "" + info.getPassengers()));
nameValuePairs.add(new BasicNameValuePair("additionalDetails", info.getAdditionalDetails()));
nameValuePairs.add(new BasicNameValuePair("lat", "" + info.getOrderLocation().getLatitudeE6()));
nameValuePairs.add(new BasicNameValuePair("lon", "" + info.getOrderLocation().getLongitudeE6()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = execute(post);
if(response == null || response.trim().length() == 0) {
throw new IOException("sendOrder_response_empty");
}
try {
JSONObject json = new JSONObject(response);
int orderId = json.getInt("orderId");
return orderId;
}
catch(JSONException e) {
throw new IOException("sendOrder_parsing: " + response);
}
}
EDIT
The execute method is public because sometimes I use custom (or dynamic) GET/POST requests.
If you have URL object you can pass to execute method:
HttpGet request = new HttpGet(url.toString());
execute(request);
As you said: the GET-Parameters are in the URL - So you can use a loadUrl() on your Webview to send them.
[..].loadUrl("http://www.example.com/data.php?param1=value1¶m2=value2&...");
The developer training docs have a good example on GET requests. You're responsible for adding the query parameters to the URL.
Post is similar, but as you said, quite different. The HttpConnectionURLConnection class can do both, and it's easy to just set the post body with an output stream.
protected String doInBackground(String... strings) {
String response = null;
String data = null;
try {
data = URLEncoder.encode("CustomerEmail", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String url = Constant.URL_FORGOT_PASSWORD;// this is url
response = ServiceHandler.postData(url,data);
if (response.equals("")){
return response;
}else {
return response;
}
}
public static String postData(String urlpath,String data){
String text = "";
BufferedReader reader=null;
try
{
// Defined URL where to send data
URL url = new URL(urlpath);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
text = sb.toString();
return text;
}
catch(Exception ex)
{
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return text;
}
private RequestListener listener;
private int requestId;
private HashMap<String, String> reqParams;
private File file;
private String fileName;
private RequestMethod reqMethod;
private String url;
private Context context;
private boolean isProgressVisible = false;
private MyProgressDialog progressDialog;
public NetworkClient(Context context, int requestId, RequestListener listener,
String url, HashMap<String, String> reqParams, RequestMethod reqMethod,
boolean isProgressVisible) {
this.listener = listener;
this.requestId = requestId;
this.reqParams = reqParams;
this.reqMethod = reqMethod;
this.url = url;
this.context = context;
this.isProgressVisible = isProgressVisible;
}
public NetworkClient(Context context, int requestId, RequestListener listener,
String url, HashMap<String, String> reqParams, File file, String fileName, RequestMethod reqMethod,
boolean isProgressVisible) {
this.listener = listener;
this.requestId = requestId;
this.reqParams = reqParams;
this.file = file;
this.fileName = fileName;
this.reqMethod = reqMethod;
this.url = url;
this.context = context;
this.isProgressVisible = isProgressVisible;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isProgressVisible) {
showProgressDialog();
}
}
#Override
protected String doInBackground(Void... params) {
try {
if (Utils.isInternetAvailable(context)) {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
clientBuilder.connectTimeout(10, TimeUnit.SECONDS);
clientBuilder.writeTimeout(10, TimeUnit.SECONDS);
clientBuilder.readTimeout(20, TimeUnit.SECONDS);
OkHttpClient client = clientBuilder.build();
if (reqMethod == RequestMethod.GET) {
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
Request request = reqBuilder.build();
Response response = client.newCall(request).execute();
String message = response.message();
String res = response.body().string();
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 1);
jObj.put("response", message);
return jObj.toString();
} else if (reqMethod == RequestMethod.POST) {
FormBody.Builder formBuilder = new FormBody.Builder();
RequestBody body = formBuilder.build();
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
reqBuilder.post(body);
Request request = reqBuilder.build();
Response response = client.newCall(request).execute();
String res = response.body().string();
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 1);
jObj.put("response", res);
return jObj.toString();
} else if (reqMethod == RequestMethod.MULTIPART) {
MediaType MEDIA_TYPE = fileName.endsWith("png") ?
MediaType.parse("image/png") : MediaType.parse("image/jpeg");
MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
multipartBuilder.setType(MultipartBody.FORM);
multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(MEDIA_TYPE, file));
RequestBody body = multipartBuilder.build();
Request.Builder reqBuilder = new Request.Builder();
reqBuilder.url(url);
reqBuilder.post(body);
Request request = reqBuilder.build();
Response response = client.newCall(request).execute();
String res = response.body().string();
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 1);
jObj.put("response", res);
return jObj.toString();
}
} else {
JSONObject jObj = new JSONObject();
jObj.put("statusCode", 0);
jObj.put("response", context.getString(R.string.no_internet));
return jObj.toString();
}
} catch (final Exception e) {
e.printStackTrace();
JSONObject jObj = new JSONObject();
try {
jObj.put("statusCode", 0);
jObj.put("response", e.toString());
} catch (Exception e1) {
e1.printStackTrace();
}
return jObj.toString();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jObj = new JSONObject(result);
if (jObj.getInt("statusCode") == 1) {
listener.onSuccess(requestId, jObj.getString("response"));
} else {
listener.onError(requestId, jObj.getString("response"));
}
} catch (Exception e) {
listener.onError(requestId, result);
} finally {
dismissProgressDialog();
}
}
private void showProgressDialog() {
progressDialog = new MyProgressDialog(context);
}
private void dismissProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}
private static NetworkManager instance = null;
private Set<RequestListener> arrRequestListeners = null;
private int requestId;
public boolean isProgressVisible = false;
private NetworkManager() {
arrRequestListeners = new HashSet<>();
arrRequestListeners = Collections.synchronizedSet(arrRequestListeners);
}
public static NetworkManager getInstance() {
if (instance == null)
instance = new NetworkManager();
return instance;
}
public synchronized int addRequest(final HashMap<String, String> params, Context context, RequestMethod reqMethod, String apiMethod) {
try {
String url = Constants.WEBSERVICE_URL + apiMethod;
requestId = UniqueNumberUtils.getInstance().getUniqueId();
NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, reqMethod, isProgressVisible);
networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (Exception e) {
onError(requestId, e.toString() + e.getMessage());
}
return requestId;
}
public synchronized int addMultipartRequest(final HashMap<String,String> params, File file, String fileName, Context context, RequestMethod reqMethod, String apiMethod) {
try {
String url = Constants.WEBSERVICE_URL + apiMethod;
requestId = UniqueNumberUtils.getInstance().getUniqueId();
NetworkClient networkClient = new NetworkClient(context, requestId, this, url, params, file, fileName, reqMethod, isProgressVisible);
networkClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (Exception e) {
onError(requestId, e.toString() + e.getMessage());
}
return requestId;
}
public void isProgressBarVisible(boolean isProgressVisible) {
this.isProgressVisible = isProgressVisible;
}
public void setListener(RequestListener listener) {
try {
if (listener != null && !arrRequestListeners.contains(listener)) {
arrRequestListeners.add(listener);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSuccess(int id, String response) {
if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
for (RequestListener listener : arrRequestListeners) {
if (listener != null)
listener.onSuccess(id, response);
}
}
}
#Override
public void onError(int id, String message) {
try {
if (Looper.myLooper() == null) {
Looper.prepare();
}
} catch (Exception e) {
e.printStackTrace();
}
if (arrRequestListeners != null && arrRequestListeners.size() > 0) {
for (final RequestListener listener : arrRequestListeners) {
if (listener != null) {
listener.onError(id, message);
}
}
}
}
public void removeListener(RequestListener listener) {
try {
arrRequestListeners.remove(listener);
} catch (Exception e) {
e.printStackTrace();
}
}
Create RequestListner intreface
public void onSuccess(int id, String response);
public void onError(int id, String message);
Get Unique Number
private static UniqueNumberUtils INSTANCE = new UniqueNumberUtils();
private AtomicInteger seq;
private UniqueNumberUtils() {
seq = new AtomicInteger(0);
}
public int getUniqueId() {
return seq.incrementAndGet();
}
public static UniqueNumberUtils getInstance() {
return INSTANCE;
}
I am not sure how to send HTTP Auth headers.
I have the following HttpClient to get requests, but not sure how I can send requests?
public class RestClient extends AsyncTask<String, Void, JSONObject> {
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the
* BufferedReader.readLine() method. We iterate until the
* BufferedReader return null which means there's no more data to
* read. Each line will appended to a StringBuilder and returned as
* String.
*/
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();
}
/*
* This is a test function which will connects to a given rest service
* and prints it's response to Android Log with labels "Praeda".
*/
public JSONObject connect(String url) {
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda", response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json = new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected JSONObject doInBackground(String... urls) {
return connect(urls[0]);
}
#Override
protected void onPostExecute(JSONObject json) {
}
}
This is covered in the HttpClient documentation and in their sample code.
Maybe the documentation of HttpClient can help: link
Since Android compiles HttpClient 4.0.x instead of 3.x, below snippet is for your reference.
if (authState.getAuthScheme() == null) {
AuthScope authScope = new Au HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);thScope(targetHost.getHostName(), targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.addRequestInterceptor(preemptiveAuth, 0);