Id likes to get HTML from the site. This site has an authentication. Authentication like this:
1) User send POST
request with username and password in body
2) Server check users body
3) If username and password are ok, server send 302 with Location
header with adress for redirect, where i can get HTML
4) User send POST
to link from Location
and gets HTML.
5) If username and password are wrong servers also sends 302, but in Location
other adress with a form for authentication .
I have a code on JavaScript and its work fine!
I want to make same on Android using OkHTTP 3.8.1
but i cant, all time i get `200 OPTIONS. Here is fine my JavaScript code:
var data = "auth-type=mo&username=SECRET&password=SECRET";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://lk.mango-office.ru/auth");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xhr.send(data);
Here is my wrong OkHTPP code:
public class MainActivity extends AppCompatActivity
{
public String postUrl = "https://lk.mango-office.ru/auth";
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try
{
postRequest(postUrl, "auth-type=mo&username=SECRET&password=SECRET" );
}
catch (IOException e)
{
e.printStackTrace();
}
}
void postRequest(String postUrl, String postBody) throws IOException
{
String str = postBody;
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(mediaType, postBody);
Request request = new Request.Builder()
.url("https://lk.mango-office.ru/auth")
.post(body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build();
client.newCall(request).enqueue(new Callback()
{
@Override
public void onFailure(Call call, IOException e)
{
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException
{
Log.d("TAG", response.body().string());
}
});
}
}