Read response from url - java

I have the url like this
enter link description here
I want to read status and sms from response. How can I do it ?
I try to use this code, but it do not work perfect
new Thread(new Runnable() {
URL url = null;
int code;
#Override
public void run() {
try {
url = new URL("http://domscanner.ru/api/poll/login?phone=79232893050");
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
Response response = call.execute();
code = response.code();
if (!response.isSuccessful()) {
code = response.code();
}
String results;
Log.i("TEST", "code " + code);
if(code == 200) {
results = response.body().toString();
} else {
results = "nothing";
}
Log.i("TEST ", "result " + results);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
in log
code 200
result
okhttp3.internal.http.RealResponseBody#90b58f4

change if else statement like below:
if(code == 200) {
results = response.body().string();
} else {
results = "nothing";
}

Related

API request returning error code 400, when i try to decode the InputStream to Bitmap before the Retrofit enqueue

I'm trying to send the POST API request to the Server like below and I'm getting the successful response code - 200, but when I try to decode the InputStream to Bitmap, then only the API requests get failed status code - 400, what went wrong with this approach
InputStream inputStream = null;
try {
inputStream = getContentResolver().openInputStream(imgUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBodyUtil.create(MediaType.get("image/" + imgType), inputStream);
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("messaging_product", “help”)
.addFormDataPart("file", "image/" + imgType, requestBody)
.addFormDataPart("type", "image/" + imgType)
.build();
//---#####if I remove the below line, then everything working fine #####
Bitmap bitmap=BitmapFactory.decodeStream(inputStream);
Log.d(TAG, "onClick: ");
Call<ModelGraphResponse> call = RetrofitInstance.getRetrofitClient().create(IService.class).uploadImageToGraph(name, body);
call.enqueue(new Callback<ModelGraphResponse>() {
#Override
public void onResponse(Call<ModelGraphResponse> call, retrofit2.Response<ModelGraphResponse> response) {
Log.d(TAG, "onResponse: ");
if (response.isSuccessful()) {
} else {
}
}
#Override
public void onFailure(Call<ModelGraphResponse> call, Throwable t) {
Log.d(TAG, "onFailure: ");
button.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
textView.setText("Failed to Upload..");
}
});
Try this once
URL url = new URL(//your URL//);
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//YOUR CODE
Bitmap img = BitmapFactory.decodeStream(is, null, options);

Android Studio give error 401 with Laravel login Api

I had an easy question, I am writing api in laravel and I will put it in my android application, but although the register part and logout part work correctly, when I check from postman in the login section, it takes the token and logs in, but when we come to the application, I get a 401 error when logging in, I wonder why? My login code is in the controller like this:
$credentials = $request->validate([
‘email’=>‘required|email’,
‘password’=>‘required’
]);
if(Auth::attempt($credentials)){
$user=Auth::user();
$token=md5(time()).‘.’.md5($request->email);
$user->forceFill([
‘api_token’=>$token,
])->save();
return response()->json([
‘token’=>$token
]);
}
return response()->json(['message'=>'The provided credentials do not match our records'],401);
}
It gives correct in Postman, it doesn't cause any problem, but I register in the application. It's not a problem. It gives 401 at login, I wonder why? My code in the application is as follows:
private void sendLogin() {
JSONObject params= new JSONObject();
try {
params.put(“email”,email);
params.put(“password”,password);
}catch (JSONException e){
e.printStackTrace();
}
String data = params.toString();
String url = getString(R.string.api_server)+"/login";
new Thread(new Runnable() {
#Override
public void run() {
Http http = new Http(LoginActivity.this,url);
http.setMethod("POST");
http.setData(data);
http.send();
runOnUiThread(new Runnable() {
#Override
public void run() {
Integer code = http.getStatusCode();
if(code == 200){
try{
JSONObject response = new JSONObject(http.getResponse());
String token = response.getString("token");
localStorage.setToken(token);
Intent i = new Intent(LoginActivity.this,UserActivity.class);
startActivity(i);
finish();
}catch (JSONException e){
e.printStackTrace();
}
}
else if(code ==422){
try{
JSONObject response = new JSONObject(http.getResponse());
String msg = response.getString("message");
alertFail(msg);
}catch (JSONException e){
e.printStackTrace();
}
}
else if(code == 401){
try{
JSONObject response = new JSONObject(http.getResponse());
String msg = response.getString("message");
alertFail(msg);
}catch (JSONException e){
e.printStackTrace();
}
}
else{
Toast.makeText(LoginActivity.this,"Error"+code,Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}
I'll be happy if you can help me
send this with headers
["Accept"] = "application/json";
["Content-Type"] = "application/json";
["withCredentials"] = true;
and in env laravel add this (values are just for example)
SESSION_DOMAIN=.localhost
SANCTUM_STATEFUL_DOMAINS=localhost,127.0.0.1

Android Check for response HTTP

I am using OKHTTP to make api calls and I realize I can use .enque for async calls and .execute for sync calls.
is there a callback to check whether the response has been received without breaking the UI or the flow of the application.
I am using the following code:
public void getItems() {
new Thread(new Runnable() {
#Override
public void run() {
OkHttpClient client = new OkHttpClient();
String url = "https://beta-pp-api.polkadoc.com/v1.0/products?category=CP&available_via=mail_order";
{
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", token)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader("X-Service-Code", "PP")
.get()
.build();
try {
Response response = client.newCall(request).execute();
groupList=getPills(response);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).start();
for getPills
public ArrayList<Group> getPills(Response response) throws JSONException {
try
{
jsonArray = new JSONArray(response.body().string());
}
catch (IOException e)
{
e.printStackTrace();
}
ArrayList<Child> childList;
ArrayList<Group> groupList = new ArrayList<Group>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
Group group = new Group();
JSONObject jsonObject = jsonArray.getJSONObject(i);
group.setPillName((String) jsonObject.get("title"));
id = jsonObject.get("id").toString();
//second api call
getPillInfo(id);
try {
JSONObject NewJSONObject = new JSONObject(secondResponse.body().string());
group.setSamePillAsData((String) NewJSONObject.getJSONObject("details").get("same_as"));
group.setPillType((String) NewJSONObject.getJSONObject("details").get("pill_type_short"));
childList = new ArrayList<Child>();
Child child = new Child();
child.setSideEffectData((String) NewJSONObject.getJSONObject("details").get("side_effects_short"));
child.setPriceData((String) NewJSONObject.getJSONObject("details").get("cost_short"));
child.setPillChoiceData((String) NewJSONObject.getJSONObject("details").get("criteria_short"));
childList.add(child);
group.setItems(childList);
groupList.add(group);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return groupList;
}
for get pillInfo():
public void getPillInfo(String id) {
OkHttpClient client = new OkHttpClient();
String url = "https://beta-pp-api.polkadoc.com/v1.0/products/" + id;
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", token)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader("X-Service-Code", "PP")
.get()
.build();
try {
secondResponse = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My UI is breaking everytime. What is going on?

How to use OKHTTP to make a post request?

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;
}

Android - How to Handle an Async Http Crash

My app is currently crashing whenever it cannot connect to the server. How do I handle this, and instead let the user know that the server is down and to try again.
private void sendPostRequest(String givenEmail, String givenPassword) {
class SendPostRequestTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String emailInput = params[0];
String passwordInput = params[1];
String jsonUserInput = "{email: " + emailInput + ", password: "
+ passwordInput + "}";
try {
HttpClient httpClient = new DefaultHttpClient();
// Use only the web page URL as the parameter of the
// HttpPost argument, since it's a post method.
HttpPost httpPost = new HttpPost(SERVER_URL);
// We add the content that we want to pass with the POST
// request to as name-value pairs
json = new JSONObject(jsonUserInput);
jsonString = new StringEntity(json.toString());
httpPost.setEntity(jsonString);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpParams httpParameters = httpPost.getParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// HttpResponse is an interface just like HttpPost.
// Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor does
// nothing.
// So we can't initialize InputStream although it is not an
// interface
InputStream inputStream = httpResponse.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
Log.i(LOGIN, "ClientProtocolException");
cpe.printStackTrace();
} catch (ConnectTimeoutException e) {
e.printStackTrace();
} catch (IOException ioe) {
Log.i(LOGIN, "IOException");
ioe.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(LOGIN, result);
try {
serverResponse = new JSONObject(result);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if ((serverResponse.has("status"))
&& (serverResponse.get("status").toString()
.equals("200"))) {
Toast.makeText(getApplicationContext(), "SUCCESS!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Incorrect Email/Password!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
SendPostRequestTask sendPostRequestTask = new SendPostRequestTask();
sendPostRequestTask.execute(givenEmail, givenPassword);
}
LogCat Error Log
11-11 16:26:14.970: I/R.id.login_button(17379): IOException
11-11 16:26:14.970: W/System.err(17379): org.apache.http.conn.HttpHostConnectException: Connection to http://* refused
11-11 16:26:14.980: W/System.err(17379): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
I can see that you are already catching the Exceptions and have a String as parameter type to onPostExecute. From inside the exceptions, you can pass a string like "error" to the onPostExecute, whenever an error occurs. Inside the onPostExecute you can check:
if the string is equal to "error":
then create a Alert dialog box from within `onPostExecute` and show it.
else:
continue as desired
Ideally a boolean would do the trick but since you already have a string, you can also use that. Otherwise you can have a struct with a string and a boolean and then pass it to onPostExecute. Hope it gives you the idea.
Or you can create new Object
public class AsyncTaskResult<T> {
private T result;
private Exception error;
public T getResult() {
return result;
}
public Exception getError() {
return error;
}
public AsyncTaskResult(T result) {
super();
this.result = result;
}
public AsyncTaskResult(Exception error) {
super();
this.error = error;
}
public void setError(Exception error) {
this.error = error;
}
}
and pass it to onPostExecute
return new AsyncTaskResult<String>(result)
or
return new AsyncTaskResult<String>(exception)
in onPostExecute you may check exception exists or not
asynctaskresult.getError() != null
You can use droidQuery to simplify everything and include HTTP error handling:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("POST")
.dataType("json")
.header("Accept", "application/json")
.header("Content-type", "application/json")
.timeout(1000)
.success(new Function() {
#Override
public void invoke($ d, Object... args) {
Toast.makeText(this, "SUCCESS!", Toast.LENGTH_SHORT).show();
JSONObject serverResponse = (JSONObject) args[0];
//handle response
}
})
.error(new Function() {
#Override
public void invoke($ d, Object... args) {
AjaxError error = (AjaxError) args[0];
//toast shows the error code and reason, such as "Error 404: Page not found"
Toast.makeText(this, "Error " + error.status + ": " + error.reason, Toast.LENGTH_SHORT).show();
}
}));

Categories

Resources