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
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.
i have wrote a method to send some data to server and receive a integer value :
private void sendOrder(Order order,String cid) {
InputStream inputStream = null;
String result = "";
int statusCode = 0;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(send_url);
JSONArray jsonArray = new JSONArray();
for (OrderDetails detail : order.getOrders()) {
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("c_id", cid);
jsonObject.accumulate("r_id", String.valueOf(detail.getR_id()));
jsonObject.accumulate("f_id", String.valueOf(detail.getF_id()));
jsonObject.accumulate("count",
String.valueOf(detail.getCount()));
jsonArray.put(jsonObject);
}
String json = jsonArray.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = Util.convertInputStreamToString(inputStream);
else
result = "0";
} catch (Exception e) {
Log.d("send order", e.toString());
}
Log.d("order result", result);
return Integer.parseInt(result);
}
the cid is numbers stored in a string like : "30111"
but in the server there is a problem in receiving c_id. its's value in server is like :"c_id":"\"30111\""
i want to c_id to be in the server as same as it is in the client.
how can i fix that ? UPDATE this is my json string in android log :
[{"count":"1","r_id":"8","f_id":"10033","c_id":"\"30111\""},{"count":"2","r_id":"8","f_id":"10034","c_id":"\"30111\""}]
This is my code, working really fine
Make a class -
public class AddQuery extends AsyncTask<Void, Void, Void> {
private Context context;
private ProgressDialog pd;
private String url;
private String jsonResult;
private String qrs;
private String cId;
public AddQuery(Context context, String qrs, String cid) {
// TODO Auto-generated constructor stub
this.context = context;
this.qrs = qrs;
this.cId = cid;
url = "http://" + context.getResources().getString(R.string.url)
+ "/ques.php";
pd = new ProgressDialog(context);
pd.setIndeterminate(true);
pd.setMessage("Retrieving Data..");
pd.setCancelable(false);
}
#Override
protected Void doInBackground(Void... arg0) {
SharedPreferences prefs = context.getSharedPreferences("com.multisoft",
Context.MODE_PRIVATE);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("go", "add"));
params.add(new BasicNameValuePair("qrs", qrs));
params.add(new BasicNameValuePair("cid", cId));
params.add(new BasicNameValuePair("uid", prefs.getString("userID", "0")));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent())
.toString();
}
catch (ClientProtocolException e) {
Log.e("e", "error1");
e.printStackTrace();
} catch (IOException e) {
Log.e("e", "error2");
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
JSONObject jsonResponse;
jsonResponse = new JSONObject(jsonResult);
//do what you want to do here from text apeared from your php and stored in jsonResult
String c_id = jsonResponse.optString("c_id");
}
execute the above class in your main activity like this-
new AddQuery(MyActivity.this, "4","23").execute();
I read some examples which are posting jsons to the server.
some one says :
OkHttp is an implementation of the HttpUrlConnection interface
provided by Java. It provides an input stream for writing content and
doesn't know (or care) about what format that content is.
Now I want to make a normal post to the URL with params of name and password.
It means I need to do encode the name and value pair into stream by myself?
As per the docs, OkHttp version 3 replaced FormEncodingBuilder with FormBody and FormBody.Builder(), so the old examples won't work anymore.
Form and Multipart bodies are now modeled. We've replaced the opaque
FormEncodingBuilder with the more powerful FormBody and
FormBody.Builder combo.
Similarly we've upgraded MultipartBuilder into
MultipartBody, MultipartBody.Part, and MultipartBody.Builder.
So if you're using OkHttp 3.x try the following example:
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("message", "Your message")
.build();
Request request = new Request.Builder()
.url("https://www.example.com/index.php")
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
}
The current accepted answer is out of date. Now if you want to create a post request and add parameters to it you should user MultipartBody.Builder as Mime Craft now is deprecated.
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("somParam", "someValue")
.build();
Request request = new Request.Builder()
.url(BASE_URL + route)
.post(requestBody)
.build();
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormEncodingBuilder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
You need to encode it yourself by escaping strings with URLEncoder and joining them with "=" and "&". Or you can use FormEncoder from Mimecraft which gives you a handy builder.
FormEncoding fe = new FormEncoding.Builder()
.add("name", "Lorem Ipsum")
.add("occupation", "Filler Text")
.build();
You can make it like this:
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, "{"jsonExample":"value"}");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Authorization", "header value") //Notice this request has header if you don't need to send a header just erase this part
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e("HttpService", "onFailure() Request was: " + request);
e.printStackTrace();
}
#Override
public void onResponse(Response r) throws IOException {
response = r.body().string();
Log.e("response ", "onResponse(): " + response );
}
});
OkHttp POST request with token in header
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("search", "a")
.addFormDataPart("model", "1")
.addFormDataPart("in", "1")
.addFormDataPart("id", "1")
.build();
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("https://somedomain.com/api")
.post(requestBody)
.addHeader("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIkMnkkMTAkZzZrLkwySlFCZlBmN1RTb3g3bmNpTzltcVwvemRVN2JtVC42SXN0SFZtbzZHNlFNSkZRWWRlIiwic3ViIjo0NSwiaWF0IjoxNTUwODk4NDc0LCJleHAiOjE1NTM0OTA0NzR9.tefIaPzefLftE7q0yKI8O87XXATwowEUk_XkAOOQzfw")
.addHeader("cache-control", "no-cache")
.addHeader("Postman-Token", "7e231ef9-5236-40d1-a28f-e5986f936877")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("response", myResponse);
progress.hide();
}
});
}
}
});
To add okhttp as a dependency do as follows
right click on the app on android studio open "module settings"
"dependencies"-> "add library dependency" -> "com.squareup.okhttp3:okhttp:3.10.0" -> add -> ok..
now you have okhttp as a dependency
Now design a interface as below so we can have the callback to our activity once the network response received.
public interface NetworkCallback {
public void getResponse(String res);
}
I create a class named NetworkTask so i can use this class to handle all the network requests
public class NetworkTask extends AsyncTask<String , String, String>{
public NetworkCallback instance;
public String url ;
public String json;
public int task ;
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public NetworkTask(){
}
public NetworkTask(NetworkCallback ins, String url, String json, int task){
this.instance = ins;
this.url = url;
this.json = json;
this.task = task;
}
public String doGetRequest() throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String doPostRequest() throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
#Override
protected String doInBackground(String[] params) {
try {
String response = "";
switch(task){
case 1 :
response = doGetRequest();
break;
case 2:
response = doPostRequest();
break;
}
return response;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
instance.getResponse(s);
}
}
now let me show how to get the callback to an activity
public class MainActivity extends AppCompatActivity implements NetworkCallback{
String postUrl = "http://your-post-url-goes-here";
String getUrl = "http://your-get-url-goes-here";
Button doGetRq;
Button doPostRq;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
doGetRq = findViewById(R.id.button2);
doPostRq = findViewById(R.id.button1);
doPostRq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.this.sendPostRq();
}
});
doGetRq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.this.sendGetRq();
}
});
}
public void sendPostRq(){
JSONObject jo = new JSONObject();
try {
jo.put("email", "yourmail");
jo.put("password","password");
} catch (JSONException e) {
e.printStackTrace();
}
// 2 because post rq is for the case 2
NetworkTask t = new NetworkTask(this, postUrl, jo.toString(), 2);
t.execute(postUrl);
}
public void sendGetRq(){
// 1 because get rq is for the case 1
NetworkTask t = new NetworkTask(this, getUrl, jo.toString(), 1);
t.execute(getUrl);
}
#Override
public void getResponse(String res) {
// here is the response from NetworkTask class
System.out.println(res)
}
}
This is one of the possible solutions to implementing an OKHTTP post request without a request body.
RequestBody reqbody = RequestBody.create(null, new byte[0]);
Request.Builder formBody = new Request.Builder().url(url).method("POST",reqbody).header("Content-Length", "0");
clientOk.newCall(formBody.build()).enqueue(OkHttpCallBack());
You should check tutorials on lynda.com. Here is an example of how to encode the parameters, make HTTP request and then parse response to json object.
public JSONObject getJSONFromUrl(String str_url, List<NameValuePair> params) {
String reply_str = null;
BufferedReader reader = null;
try {
URL url = new URL(str_url);
OkHttpClient client = new OkHttpClient();
HttpURLConnection con = client.open(url);
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(getEncodedParams(params));
writer.flush();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reply_str = sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
// try parse the string to a JSON object. There are better ways to parse data.
try {
jObj = new JSONObject(reply_str);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
//in this case it's NameValuePair, but you can use any container
public String getEncodedParams(List<NameValuePair> params) {
StringBuilder sb = new StringBuilder();
for (NameValuePair nvp : params) {
String key = nvp.getName();
String param_value = nvp.getValue();
String value = null;
try {
value = URLEncoder.encode(param_value, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
return sb.toString();
}
protected Void doInBackground(String... movieIds) {
for (; count <= 1; count++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Resources res = getResources();
String web_link = res.getString(R.string.website);
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("name", name)
.add("bsname", bsname)
.add("email", email)
.add("phone", phone)
.add("whatsapp", wapp)
.add("location", location)
.add("country", country)
.add("state", state)
.add("city", city)
.add("zip", zip)
.add("fb", fb)
.add("tw", tw)
.add("in", in)
.add("age", age)
.add("gender", gender)
.add("image", encodeimg)
.add("uid", user_id)
.build();
Request request = new Request.Builder()
.url(web_link+"edit_profile.php")
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
JSONObject object = array.getJSONObject(0);
hashMap.put("msg",object.getString("msgtype"));
hashMap.put("msg",object.getString("msg"));
// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Here is my method to do post request
first pass in method map and data like
HashMap<String, String> param = new HashMap<String, String>();
param.put("Name", name);
param.put("Email", email);
param.put("Password", password);
param.put("Img_Name", "");
final JSONObject result = doPostRequest(map,Url);
public static JSONObject doPostRequest(HashMap<String, String> data, String url) {
try {
RequestBody requestBody;
MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
if (data != null) {
for (String key : data.keySet()) {
String value = data.get(key);
Utility.printLog("Key Values", key + "-----------------" + value);
mBuilder.addFormDataPart(key, value);
}
} else {
mBuilder.addFormDataPart("temp", "temp");
}
requestBody = mBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Utility.printLog("URL", url);
Utility.printLog("Response", responseBody);
return new JSONObject(responseBody);
} catch (UnknownHostException | UnsupportedEncodingException e) {
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
Log.e(TAG, "Error: " + e.getLocalizedMessage());
} catch (Exception e) {
e.printStackTrace();
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
}
return null;
}
Add the following to the build.gradle
compile 'com.squareup.okhttp3:okhttp:3.7.0'
Create a new thread, in the new thread add the following code.
OkHttpClient client = new OkHttpClient();
MediaType MIMEType= MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create (MIMEType,"{}");
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = client.newCall(request).execute();
As for Kotlin in 2022 (POST request) works:
val client = OkHttpClient()
val formBody: RequestBody = MultipartBody.Builder()
.addFormDataPart("phone", editText1.text.toString())
.addFormDataPart("email", editText2.text.toString())
.build()
val request: Request = Request.Builder()
.url("https://hellokitty.com/users")
.post(formBody)
.build()
try {
// Do something with the response.
val response = client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: okio.IOException) {
print(e.message)
}
override fun onResponse(call: Call, response: Response) {
print(response.message)
print("XXX \n" + response.body)
}
})
editTextResponse.text = response.toString()
} catch (e: java.io.IOException) {
editTextResponse.text = e.toString()
e.printStackTrace()
}
Gradle:
implementation("com.squareup.okhttp3:okhttp:5.0.0-alpha.6")
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jaskierltd.blablaApp">
<uses-permission android:name="android.permission.INTERNET"/>
...
If you want to post parameter in okhttp as body content which can be encrypted string with content-type as "application/x-www-form-urlencoded" you can first use URLEncoder to encode the data and then use :
final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("application/x-www-form-urlencoded");
okhttp3.Request request = new okhttp3.Request.Builder()
.url(urlOfServer)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, yourBodyDataToPostOnserver))
.build();
you can add header according to your requirement.
public static JSONObject doPostRequestWithSingleFile(String url,HashMap<String, String> data, File file,String fileParam) {
try {
final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody requestBody;
MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
for (String key : data.keySet()) {
String value = data.get(key);
Utility.printLog("Key Values", key + "-----------------" + value);
mBuilder.addFormDataPart(key, value);
}
if(file!=null) {
Log.e("File Name", file.getName() + "===========");
if (file.exists()) {
mBuilder.addFormDataPart(fileParam, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
}
}
requestBody = mBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
String result=response.body().string();
Utility.printLog("Response",result+"");
return new JSONObject(result);
} catch (UnknownHostException | UnsupportedEncodingException e) {
Log.e(TAG, "Error: " + e.getLocalizedMessage());
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, "Other Error: " + e.getMessage());
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
public static JSONObject doGetRequest(HashMap<String, String> param,String url) {
JSONObject result = null;
String response;
Set keys = param.keySet();
int count = 0;
for (Iterator i = keys.iterator(); i.hasNext(); ) {
count++;
String key = (String) i.next();
String value = (String) param.get(key);
if (count == param.size()) {
Log.e("Key",key+"");
Log.e("Value",value+"");
url += key + "=" + URLEncoder.encode(value);
} else {
Log.e("Key",key+"");
Log.e("Value",value+"");
url += key + "=" + URLEncoder.encode(value) + "&";
}
}
/*
try {
url= URLEncoder.encode(url, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}*/
Log.e("URL", url);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response responseClient = null;
try {
responseClient = client.newCall(request).execute();
response = responseClient.body().string();
result = new JSONObject(response);
Log.e("response", response+"==============");
} catch (Exception e) {
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("status","false");
jsonObject.put("message",e.getLocalizedMessage());
return jsonObject;
} catch (JSONException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
return result;
}
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");
...