I try to delete a parameter with this :
private class SendfeedbackDeleteStudio extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "DeleteStudio";
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String venid = params[0];
Utils.log("venid: " + venid);
final String url_delete_studio = Constant.URI_BASE_FAVOURITE;
String contentType;
contentType = "application/x-www-form-urlencoded";
// do above Server call here
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("vendor_id", venid));
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpDelete httpDelete = new HttpDelete(url_delete_studio);
httpDelete.setHeader("Content-Type", contentType);
httpDelete.setHeader("Authorization", "Bearer " + token);
httpDelete.setHeader("Accept", "application/json");
httpDelete.setHeader("Accept-Charset", "utf-8");
httpDelete.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpDelete);
HttpEntity entity = response.getEntity();
if (entity != null) {
// EntityUtils to get the reponse content
String content = EntityUtils.toString(entity);
Utils.log("daftar content: " + content);
JSONObject hasiljson = new JSONObject(content);
Utils.log("hasiljson object: " + hasiljson);
String success = hasiljson.getString("success");
Utils.log("success: " + success);
}
// writing response to log
Log.d("Http Response:", response.toString());
}
catch (Exception e)
{
Log.e(LOG_TAG, String.format("Error during delete: %s", e.getMessage()));
}
return "processing";
}
#Override
protected void onPostExecute(String message) {
//process message
clickFavourites();
}
}
but it get red on httpDelete.setEntity(new UrlEncodedFormEntity(nameValuePair));, it seems it cannot recognize the parameter that I sent to delete. How to delete venid parameter?
HTTP DELETE acts like GET variant so it won't take any inputs.
If you are looking to provide a delete with a body, you might want to consider using a POST to a location that accepts a body.
or you can use this
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
import org.apache.http.annotation.NotThreadSafe;
#NotThreadSafe
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
public String getMethod() { return METHOD_NAME; }
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() { super(); }
}
which is referred from here
Related
I have a client Class that connects to the server and sends a POST request and in response gets a Json answer.
public class ClientLocal extends AsyncTask<Void, Void, String> {
private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8"); //Media type for request
public JSONObject all_info_json;
private String page;
private SharedPreferences prefs;
private String login;
private String pass;
private StringBuilder request_body = new StringBuilder();
private OkHttpClient client = new OkHttpClient();
protected String doInBackground(Void... params) {
RequestBody body = RequestBody.create(JSON, request_body.toString());
Request request = new Request.Builder()
.url("https://program.yousystem.com.ua/frontend/api/user/login")
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
page = response.body().string();
//Log.i("PAGE", "page from try" + page);
return page;
} catch (IOException e) {
Log.i("ERROR", "1" + e.toString());
e.printStackTrace();
return null;
}
}
protected void onPostExecute(String page) {
try {
all_info_json = (JSONObject) new JSONTokener(page).nextValue();
JSONObject response = all_info_json.getJSONObject("response");
Log.i("PAGE", "RESP" + response.toString());
String token = response.getString("token");
Log.i("PAGE", "TOKEN " + token);
JSONObject profile = response.getJSONObject("profile");
Log.i("PAGE", "PROFILE" + profile.toString());
JSONArray balances = profile.getJSONArray("balances");
JSONObject balance_obj = balances.getJSONObject(0);
String balance = balance_obj.getString("balance");
Log.i("PAGE", "Balance" + balance);
JSONObject person = profile.getJSONObject("person");
String firstName = person.getString("firstName");
String lastName = person.getString("lastName");
String mobile = person.getString("mobile");
String email = person.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
// Log.i("PAGE", "page from post" + page);
}
ClientLocal(String login, String pass) {
this.login = login;
this.pass = pass;
this.request_body.append("{username: \"");
this.request_body.append(login);
this.request_body.append("\", pass: \"");
this.request_body.append(pass);
this.request_body.append("\", lng: \"ua\", prgCode: \"prg1\"}\"");
Log.i("", "page constructor" + request_body.toString());
}}
I need to execute all requests in one Client Class using AsyncTask, can anyone help me, how to do this? Because to run a request I use ClientLocal client = new ClientLocal("login","pass"); and after that client.execute();
In my opinion I need to create Request builder class. But how to use it in Client local?
public class RequestBuilder {
final private static String login_string = "https://program.yousystem.com.ua/frontend/api/user/login";
final private static String about_me = "https://program.yousystem.com.ua/frontend/api/user/me";
final private static String about_me_edit = "https://program.yousystem.com.ua/frontend/api/user/save";
final private static String transaction_list = "https://program.yousystem.com.ua/frontend/api/transaction/list";
String card_number;
String password;
StringBuilder request_body_login = new StringBuilder();
public RequestBuilder(String card_number_, String password_) {
this.card_number = card_number_;
this.password = password_;
}
public String LoginRequest(){
this.request_body_login.append("{username: \"");
this.request_body_login.append(card_number);
this.request_body_login.append("\", pass: \"");
this.request_body_login.append(password);
this.request_body_login.append("\", lng: \"ua\", prgCode: \"prg1\"}\"");
Log.i("", "page constructor" + request_body_login.toString());
return request_body_login.toString();
}}
Login request
Post https://program.yousystem.com.ua/frontend/api/user/login
Request {
"username": "username",
"pass": "pass",
"lng": "ua",
"prgCode": "prg1"
}
Get profile info
Post https://program.yousystem.com.ua/frontend/api/user/me
Request {
"prgCode": "prg1",
"token": "XT4PHNZBMSK73C7KH33NDJCN8A4SP5CJ"
}
Transaction list
Post https://program.yousystem.com.ua/frontend/api/transaction/list
Request {
"withLimit": true,
"prgCode": "prg1",
"token": "XT4PHNZBMSK73C7KH33NDJCN8A4SP5CJ"
}
You can have a class with the methods for each request
public class MyRequests{
private jsonParser;
public MyRequests(){
jsonParser = new JSONParser()
}
//request login
public JSONObject loginRequest(String username,String password, String prgCode, String language){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("prgCode", prgCode));
params.add(new BasicNameValuePair("lang", language));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
return json;
}
//request profile info
public JSONObject profileRequest(String prgCode,String token){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("prgCode", prgCode));
params.add(new BasicNameValuePair("token", token));
JSONObject json = jsonParser.getJSONFromUrl(profileURL, params);
return json;
}
}
Then you can call each one in their respective activity in asyncTask
protected String doInBackground(String... args){
MyRequests request = new MyRequest();
jsonObject = request.loginRequest(username,password);
//handle json object here
return null;
}
I am struggling in finding a replacement for the deprecated DefaultHttpClient and connected classes liken HttpPost etc.
In a first attempt, I tried using the volley library, but nothing seemed to work, so after a bit research I am trying now with Retrofit 1.9.
In my app, I connect to a own restful client. Here is the old code (example POST), which works perfectly well:
private static DefaultHttpClient httpClient = new DefaultHttpClient();
public static String executePOST(Map<String, String> postParams, int connTO, int sockTO, String uri){
String res, message;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connTO);
HttpConnectionParams.setSoTimeout(httpParams, sockTO);
HttpConnectionParams.setTcpNoDelay(httpParams, true);
httpClient.setParams(httpParams);
HttpPost httppost = new HttpPost(uri);
JSONObject json = new JSONObject();
try {
Iterator<Entry<String, String>> iterator = postParams.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> pair = (Map.Entry<String, String>)iterator.next();
json.put(pair.getKey(), pair.getValue());
}
message = json.toString();
httppost.setEntity(new StringEntity(message, "UTF8"));
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
res = EntityUtils.toString(entity).trim();
} catch (ClientProtocolException e) {
res = "Client Protocol Exception";
} catch (IOException e) {
res = e.getLocalizedMessage();
} catch (JSONException e){
res = e.getLocalizedMessage();
}
return res;
}
I send the request like this from my Activity
Map<String, String> arguments = new HashMap<String, String>();
arguments.put("email", username);
new HttpClient(arguments, new LoginActivityCommunicationListener(this, LoginOperation.EMAIL_CHECK), URI_ROOT + "/kunde", 0).execute();
The listener in the arguments handles the response callback, the 0 means POST.
this results in a JSON response, having the fields id and person
So I tried to implement a Retrofit variant of above like this
MyApi.java
public interface MyDosAPI {
#FormUrlEncoded
#POST("/kunde")
public void checkEmail(#Field("email") String email, Callback<EmailCheck> response);
}
EmailCheck.java
public class EmailCheck {
#SerializedName("id")
private String id;
#SerializedName("person")
private String person;
public void setId(String id){
this.id = id;
}
public void setPerson(String person){
this.person = person;
}
public String getId(){
return id;
}
public String getPerson(){
return person;
}
}
and in the activity
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(URI_ROOT)
.build();
MyDosAPI api = adapter.create(MyDosAPI.class);
api.checkEmail(username, new Callback<EmailCheck>() {
#Override
public void success(EmailCheck emailChecks, Response response) {
Log.i("MyCount", "success");
}
#Override
public void failure(RetrofitError error) {
Log.i("MyCount", error.getMessage());
}
});
result
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
obviously there is something essential that I am missing. Is there - apart of Retrofit or Volley - another solution where I can define the requests like I did before?
Change to:
public interface MyDosAPI {
#POST("/kunde")
public void checkEmail(#Body String email, Callback<EmailCheck> response);
}
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 carry out the following php query on my remote database
$result = mysqli_query($con->myconn, "SELECT id, stake, user, returns, teams, status FROM `bet` WHERE user = $user") or die(mysql_error());
My only problem is I'm not sure how to modify my JSONParser class so that I can simultaneously pass the user parameter to the database and receive the results. It currently looks like this and allows me only to either retrieve values or send values.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
CODE :
public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games = "***";
JSONParser jParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_GAMELIST = "gamelist";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
JSONArray allgames = null;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
// Hashmap for ListView
ArrayList<HashMap<String, String>> gamesList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
class LoadAllGames extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
*/
/**
* Before starting background thread Show Progress Dialog
*//*
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayAllBets.this);
pDialog.setMessage("Loading Bets. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
*/
/**
* getting All products from url
*//*
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Games: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Games
allgames = json.getJSONArray(TAG_GAMELIST);
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
id = c.getString(TAG_ID);
stake = c.getString(TAG_STAKE);
returns = c.getString(TAG_RETURNS);
status = c.getString(TAG_STATUS);
teams = c.getString(TAG_TEAMS);;
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, teams);
map.put(TAG_STAKE, stake);
map.put(TAG_RETURNS, returns);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
gamesList.add(map);
}
// } else {
// no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return "";
}
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;
}