HTTP POST request in Android causing server to crash - android

I'm pulling my hair out trying to get this to work. I'm using OkHTTP to make a POST request to my server. However, every method I've tried of making a successful POST request with parameters, causes the server to go down, giving me a response of '503 service unavailable'. I use exterior clients to test the server, like the Advanced Rest Client extension, and it works perfectly fine.
The URL for the API is in the format of "https://mystuff-herokuapp.com/postuser" and my body parameters are "user_id", "userName", "email". I've tried adding headers to the request, changing from FormBodyEncoding() to MultiPartBuilder(), etc etc.
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//set toolbar as the acting action bar
Toolbar actionToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(actionToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Intent intent = getIntent();
String photoUrl = intent.getStringExtra("photo");
String userTwitterID = intent.getStringExtra("userID");
String userName = intent.getStringExtra("name");
String userEmail = intent.getStringExtra("email");
JSONObject jObject = new JSONObject();
try {
jObject.put("user_id", userTwitterID);
jObject.put("userName", userName);
jObject.put("userEmail", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
new UserApiProcess().execute(jObject);
}
Async Task
private class UserApiProcess extends AsyncTask<Object, Void, Void>{
#Override
protected Void doInBackground(Object... strings) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new MultipartBuilder()
.addFormDataPart("user_id", "800")
.addFormDataPart("userName", "Nick")
.addFormDataPart("email", "something#something.com")
.build();
Request request = new Request.Builder()
.url("https://mystuff.herokuapp.com/postuser")
.addHeader("Content-Type", "x-www-form-urlencoded")
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Successful Response from Advanced Rest Client
My Server Error through Android

Try this. It should work.
private class UserApiProcess extends AsyncTask<Object, Void, Void>{
#Override
protected Void doInBackground(Object... strings) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormEncodinBuilder()
.add("user_id", "800")
.add("userName", "Nick")
.add("email", "something#something.com")
.build();
Request request = new Request.Builder()
.url("https://mystuff.herokuapp.com/postuser")
.addHeader("Content-Type", "x-www-form-urlencoded")
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

Related

OKHTTP how to pass JSON to FormBody [duplicate]

So, back when I was using Koush's Ion, I was able to add a json body to my posts with a simple .setJsonObjectBody(json).asJsonObject()
I'm moving over to OkHttp, and I really don't see a good way to do that. I'm getting error 400's all over the place.
Anyone have any ideas?
I've even tried manually formatting it as a json string.
String reason = menuItem.getTitle().toString();
JsonObject json = new JsonObject();
json.addProperty("Reason", reason);
String url = mBaseUrl + "/" + id + "/report";
Request request = new Request.Builder()
.header("X-Client-Type", "Android")
.url(url)
.post(RequestBody
.create(MediaType
.parse("application/json"),
"{\"Reason\": \"" + reason + "\"}"
))
.build();
client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
#Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException(
"Unexpected code " + response);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});
}
});
/*Ion.with(getContext(), url)
.setHeader("X-Client-Type", "Android")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});*/
Just use JSONObject.toString(); method.
And have a look at OkHttp's tutorial:
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON); // new
// RequestBody body = RequestBody.create(JSON, json); // old
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
You can create your own JSONObject then toString().
Remember run it in the background thread like doInBackground in AsyncTask.
OkHttp version > 4:
import okhttp3.MediaType.Companion.toMediaType
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build()
var response: Response? = null
try {
response = client.newCall(request).execute()
val resStr = response.body!!.string()
} catch (e: IOException) {
e.printStackTrace()
}
OkHttp version 3:
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
Another approach is by using FormBody.Builder().
Here's an example of callback:
Callback loginCallback = new Callback() {
#Override
public void onFailure(Call call, IOException e) {
try {
Log.i(TAG, "login failed: " + call.execute().code());
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// String loginResponseString = response.body().string();
try {
JSONObject responseObj = new JSONObject(response.body().string());
Log.i(TAG, "responseObj: " + responseObj);
} catch (JSONException e) {
e.printStackTrace();
}
// Log.i(TAG, "loginResponseString: " + loginResponseString);
}
};
Then, we create our own body:
RequestBody formBody = new FormBody.Builder()
.add("username", userName)
.add("password", password)
.add("customCredential", "")
.add("isPersistent", "true")
.add("setCookie", "true")
.build();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(this)
.build();
Request request = new Request.Builder()
.url(loginUrl)
.post(formBody)
.build();
Finally, we call the server:
client.newCall(request).enqueue(loginCallback);
In kotlin, in okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc

Android Asynctask addheader

I am trying to connect with my webservice restful to login a user.
i do that:
private class LoginTask extends AsyncTask {
OkHttpClient client = new OkHttpClient();
String base64NamePass;
public LoginTask(String base64NamePass){
this.base64NamePass = base64NamePass;
}
#Override
protected Object doInBackground(Object[] params) {
Response response = null;
try {
response = get("http://192.168.0.27:8080/ServicioRestTFG/rest/UsuariosServicesRs/login", base64NamePass);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
private Response get (String url, String base64NamePass) throws IOException {
Request request = new Request.Builder()
.get()
.url(url)
.addHeader("Authorization", base64NamePass)
.build();
return client.newCall(request).execute();
}
}
First i encoded the user and the pass with base64 and then i send it to my server.
But when i add the header:
Request request = new Request.Builder()
.get()
.url(url)
.addHeader("Authorization", base64NamePass)
.build();
return client.newCall(request).execute();
the app forceclosed and it doesnt show me what is the error, only close.
Any idea?
thanks

OKHTTP is secure?

I am building an android app that needs to log the user to our server and the connection needs to be secure (HTTPs). My question is, should I use OKHTTP library for this purpose?
I use the library to log a user as follows:
public class MainActivity extends AppCompatActivity {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private static final String TAG = MainActivity.class.getSimpleName();
private JSONObject responseJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final JSONObject myJson = new JSONObject();
try {
myJson.put("udid","c376e418-da42-39fb-0000-d821f1fd2804");
myJson.put("email","email
myJson.put("password","password");
} catch (JSONException e) {
e.printStackTrace();
}
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
//Your code goes here
String response = post("https://ADDRESS/v1/auth", myJson.toString());
responseJson = new JSONObject(response);
String message = responseJson.getString("message");
String token = responseJson.getString("token");
Log.d(TAG,"Response message: " + message);
Log.d(TAG,"Response token: " + token);
Log.d("MainActivity",response);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
String post(String url, String json) throws IOException {
OkHttpClient client = new OkHttpClient();
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();
}
}
should I use OKHTTP library for this purpose?
OkHttp supports https URLs, as do most HTTP client libraries for Android.

OkHttp Post Body as JSON

So, back when I was using Koush's Ion, I was able to add a json body to my posts with a simple .setJsonObjectBody(json).asJsonObject()
I'm moving over to OkHttp, and I really don't see a good way to do that. I'm getting error 400's all over the place.
Anyone have any ideas?
I've even tried manually formatting it as a json string.
String reason = menuItem.getTitle().toString();
JsonObject json = new JsonObject();
json.addProperty("Reason", reason);
String url = mBaseUrl + "/" + id + "/report";
Request request = new Request.Builder()
.header("X-Client-Type", "Android")
.url(url)
.post(RequestBody
.create(MediaType
.parse("application/json"),
"{\"Reason\": \"" + reason + "\"}"
))
.build();
client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
#Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException(
"Unexpected code " + response);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});
}
});
/*Ion.with(getContext(), url)
.setHeader("X-Client-Type", "Android")
.setJsonObjectBody(json)
.asJsonObject()
.setCallback(new FutureCallback<JsonObject>() {
#Override
public void onCompleted(Exception e, JsonObject result) {
Toast.makeText(context, "Report Received", Toast.LENGTH_SHORT).show();
}
});*/
Just use JSONObject.toString(); method.
And have a look at OkHttp's tutorial:
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(json, JSON); // new
// RequestBody body = RequestBody.create(JSON, json); // old
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
You can create your own JSONObject then toString().
Remember run it in the background thread like doInBackground in AsyncTask.
OkHttp version > 4:
import okhttp3.MediaType.Companion.toMediaType
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
val client = OkHttpClient()
val mediaType = "application/json; charset=utf-8".toMediaType()
val body = jsonObject.toString().toRequestBody(mediaType)
val request: Request = Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build()
var response: Response? = null
try {
response = client.newCall(request).execute()
val resStr = response.body!!.string()
} catch (e: IOException) {
e.printStackTrace()
}
OkHttp version 3:
// create your json here
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("KEY1", "VALUE1");
jsonObject.put("KEY2", "VALUE2");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("https://YOUR_URL/")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
Another approach is by using FormBody.Builder().
Here's an example of callback:
Callback loginCallback = new Callback() {
#Override
public void onFailure(Call call, IOException e) {
try {
Log.i(TAG, "login failed: " + call.execute().code());
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// String loginResponseString = response.body().string();
try {
JSONObject responseObj = new JSONObject(response.body().string());
Log.i(TAG, "responseObj: " + responseObj);
} catch (JSONException e) {
e.printStackTrace();
}
// Log.i(TAG, "loginResponseString: " + loginResponseString);
}
};
Then, we create our own body:
RequestBody formBody = new FormBody.Builder()
.add("username", userName)
.add("password", password)
.add("customCredential", "")
.add("isPersistent", "true")
.add("setCookie", "true")
.build();
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(this)
.build();
Request request = new Request.Builder()
.url(loginUrl)
.post(formBody)
.build();
Finally, we call the server:
client.newCall(request).enqueue(loginCallback);
In kotlin, in okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc

How to make a POST HTTPs (with JSON) request in Android?

I am looking for a way how to make a POST (login) https request in android. How to make sure that the code don't trust self-signed/invalid certs. The input to the request needs to be in the following format:
{
"udid": DEVICE_ID
"email": "email#email.com",
"password": "password"
}
I need to make the auth call to this address format:
https://api.ADDRESS.com/v1/auth
Please note that I want to use HTTPs request and not HTTP.
You can use volley/retrofit library for parsing json.
example #
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
I ended up using OkHTTP after researching if it is secure to use in my case:
public class MainActivity extends AppCompatActivity {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private static final String TAG = MainActivity.class.getSimpleName();
private JSONObject responseJson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final JSONObject myJson = new JSONObject();
try {
myJson.put("udid","c376e418-da42-39fb-0000-d821f1fd2804");
myJson.put("email","email
myJson.put("password","password");
} catch (JSONException e) {
e.printStackTrace();
}
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
//Your code goes here
String response = post("https://ADDRESS/v1/auth", myJson.toString());
responseJson = new JSONObject(response);
String message = responseJson.getString("message");
String token = responseJson.getString("token");
Log.d(TAG,"Response message: " + message);
Log.d(TAG,"Response token: " + token);
Log.d("MainActivity",response);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
String post(String url, String json) throws IOException {
OkHttpClient client = new OkHttpClient();
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();
}
}

Categories

Resources