I want wit.ai analysing my sentences. When I send the String "where is the door" wit.ai should answer with a JSON which includes that my sentence has the intent : navigation. But unfortunately the wit.ai log says that there is no request going in. What am I doing wrong? The parameters are right, but maybe they are in a false order?
public class MainActivity extends AppCompatActivity {
String addressM = "https://api.wit.ai/message";
String accessToken = "xxxxxxxxxxxxxxxxxxxxccc";
String header = "Authorization: Bearer ";
String query = "q";
String message = "where is the door";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
final TextView textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute(addressM);
}
});
}
private class JSONTask extends AsyncTask<String, String, String >{
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("access_token", "xxxxxxxxxxxxxxxxxxxxxxx");
connection.setRequestProperty("q", message);
connection.setRequestMethod("POST");
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) !=null){
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null){
connection.disconnect();
}
try {
if (reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(result);
Toast.makeText(MainActivity.this, result,
Toast.LENGTH_LONG).show();
}
}
}
Here is a example what the reponse should be. Relevant for me is that the intent is navigation
[
{
"entities":
{
"intent":
[
{
"confidence":
0.92597581019421
"value":
{
"value":
"navigation"
}
"entity":
"intent"
}
]
}
"confidence":
null
"_text":
"where is the door"
"intent":
"default_intent"
"intent_id":
"default_intent_id"
}
]
You should be passing the parameters as query parameters, not as HTTP headers. Also the access token should be passed in an authorization HTTP header.
Try this:
Uri uri = Uri.parse(addressM)
.buildUpon()
.appendQueryParameter("q", message)
.build();
URL url = new URL(uri.toString());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Bearer " + myAccessToken);
connection.setRequestMethod("POST");
connection.connect();
If you want to make your life easier using HTTP APIs consider using retrofit (I haven't tried to see if Wit's API is friendly to it), or at the very least try OkHttp.
static final String MESSAGE_BASE_URL = "https://api.wit.ai/message";
static final String MY_ACCESS_TOKEN = "...";
private final OkHttpClient client = new OkHttpClient();
...
HttpUrl url = HttpUrl.parse(MESSAGE_BASE_URL)
.newBuilder()
.addQueryParameter("q", message)
.build();
Request request = new Request.Builder()
.url(url)
.addHeader("authorization", "Bearer " + MY_ACCESS_TOKEN)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
Related
So I have been trying to workout an authentication system for my app. I have a REST API running, which is tested to work with Oauth2 authentication using CURL from my laptop, so that I can get tokens for the API.
My result variable within the doInBackground does get a JSON response from my API, giving the access token information, its life, etc.
Like I get this value in result when I debug:
{"access_token":"4Oq6o8oAGRf4oflu3hrbsy18qeIfG1","expires_in":36000,"token_type":"Bearer","scope":"read write","refresh_token":"iocSNJ2PTVbph2RnWmcf0Zv69PDKjw"}
However, my onPostExecute for some reason is not getting called.
Here is my code.
login.java
public class Login extends AppCompatActivity {
Button LoginButton, RegButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
RegButton = (Button) findViewById(R.id.LoginRegister);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/auth/token/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
RegButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
startActivity(new Intent(Login.this, Register.class));
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
try {
// Putting the data to be posted in the Django API
AuthHelper.execute(un, pw, url);
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
WSAdapter.java
public class WSAdapter {
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
//String data = "";
StringBuilder result = new StringBuilder();
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[2]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept","application/json");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// Tells the URL that I want to read the response data
httpURLConnection.setDoInput(true);
// JSON object for the REST API
JSONObject jsonParam = new JSONObject();
jsonParam.put("client_id", "mYIHBd321Et3sgn7DqB8urnyrMDwzDeIJxd8eCCE");
jsonParam.put("client_secret", "qkFYdlvikU4kfhSMBoLNsGleS2HNVHcPqaspCDR0Wdrdex5dHyiFHPXctedNjugnoTq8Ayx7D3v1C1pHeqyPh1BjRlBTQiJYSuH6pi9EVeuyjovxacauGVeGdsBOkHI3");
jsonParam.put("username", params[0]);
jsonParam.put("password", params[1]);
jsonParam.put("grant_type", "password");
Log.i("JSON", jsonParam.toString());
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes(jsonParam.toString());
// Flushes the jsonParam to the output stream
wr.flush();
wr.close();
// // Representing the input stream
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// reading the input stream / response from the url
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", result.toString());
return result.toString();
}
#Override
protected void onPostExecute(String result) {
//super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
}
}
SO I actually just figured this out. It turns out that my code is running fine, its just that when I debug, I didn't realize theres a button to the side "Run the new thread" or something like that. It then sent me to the onPostExecute. Sorry for being a noob. Hopefully this can be a help to somebody in the future with this simple mistake.
I am new to asynchronous tasks and trying to create a login UI. When I make a request from the server with valid credentials, everything works fine. When the credentials are incorrect, I use a set of "if" statements to check what the error code of the response is and print the corresponding message. I also have such a message for the case that the response is empty. I can see from the part of the server that all the responses include status codes, even when the credentials are invalid. Furthermore I can see the status code by using checkpoints in my code. But when I try to extract the status code from a response I got for invalid credentials, the only "if" statement that works is the one checking if the response is equal to "". None of the conditions of the other "if" statements are fulfilled even when they should be. Here is my code:
public String GET(String u) {
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String line;
String jsonString = "";
try {
URL url = new URL(u);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
httpURLConnection.disconnect();
}
return jsonString;
}
public void ProcessResponse(String response) {
if(response!="") {
try {
json = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
status = json.getInt("status_code");
if (status == 500) {
Toast.makeText(this, "Internal server error! Please repeat action!", Toast.LENGTH_SHORT).show();
} else if(status == 401) {
Toast.makeText(this, "Invalid credentials", Toast.LENGTH_SHORT).show();
} else if(status == 400) {
Toast.makeText(this, "Bad Request! Please repeat action!", Toast.LENGTH_SHORT).show();
} else if(status == 200) {
try {
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("base_url", baseURL);
editor.putInt("store_id", json.getInt("store_id"));
editor.putInt("pin", json.getInt("pin_number"));
editor.putInt("delete_table",json.getInt("delele_table_id"));
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), APICall.class);
intent.putExtra("Action","Main Menu");
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(LoginActivity.this, "Problem encountered!", Toast.LENGTH_SHORT).show();
}
}
private class ServerCall extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String url = params[0];
return GET(url);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ProcessResponse(s);
}
}
These functions are called in another part of the code with the execute function as usually done in AsyncTask.
Thank you in advance for your help people!
Edit: The function is called like this:
public class LoginActivity extends AppCompatActivity {
public static final String MY_PREFS_NAME = "Shared Preferences";
String url = "";
String baseURL = "";
int status = 0;
JSONObject json = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.login_button);
CheckBox mode = (CheckBox) findViewById(R.id.login_development_mode);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText developerURL = (EditText) findViewById(R.id.base_url);
EditText store = (EditText) findViewById(R.id.store_id_field);
EditText pin = (EditText) findViewById(R.id.pin_field);
baseURL = developerURL.getText().toString();
url = baseURL + "/api/auth/check?store_id="+store.getText().toString()+
"&pin_number="+pin.getText().toString();
ServerCall loginCall = new ServerCall();
loginCall.execute(url);
}
});
/*more code, including the AsyncTask mentioned above*/
}
I found the answer to my problem. Thank you all for responding. I changed the GET and processResponse methods as follows:
public String GET(String u) {
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String line;
String jsonString = "";
int code = -1;
try {
URL url = new URL(u);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
code = httpURLConnection.getResponseCode();
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
status = code;
return "";
} finally {
httpURLConnection.disconnect();
}
return jsonString;
}
public void ProcessResponse(String response) {
if (status == 500) {
Toast.makeText(this, "Internal server error! Please repeat action!", Toast.LENGTH_SHORT).show();
} else if(status == 401) {
Toast.makeText(this, "Invalid credentials", Toast.LENGTH_SHORT).show();
} else if(status == 400) {
Toast.makeText(this, "Bad Request! Please repeat action!", Toast.LENGTH_SHORT).show();
} else if(status == 200) {
if(response!="") {
try {
json = new JSONObject(response);
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("base_url", baseURL);
editor.putInt("store_id", json.getInt("store_id"));
editor.putInt("cell_phone", json.getInt("cell_phone"));
editor.putInt("pin", json.getInt("pin_number"));
editor.putInt("delete_table", json.getInt("delele_table_id"));
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), APICall.class);
intent.putExtra("Action","Main Menu");
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "Problem encountered!", Toast.LENGTH_SHORT).show();
}
}
}
I am not sure if the way I used the httpURLConnection is the most efficient or if my code is just stupid, but it works, so if anyone has any suggestions to improve it, feel free! Thank you all again!
I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}
I have created a fragment which if it is activated it will show MySQL data but it takes time to fetch the data and show it on a custom ListView.
I tried to implement AsyncTask so that while fetching the data you can do something else on the fragment while waiting but am having this error.
"FATAL EXCEPTION: main java.lang.NullPointerException"
Here is the code
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_markets,container,false);
//lvMarkets.setAdapter(new CustomAdapter(getActivity().getApplicationContext(),Symbols,Prices,Balances));
DBHelper db = new DBHelper(getActivity().getApplicationContext());
final ListView lvMarkets = (ListView)getActivity().findViewById(R.id.lvMarkets);
final String c_androidid = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
final Cursor rs = db.getID(c_androidid);
rs.moveToFirst();
final String c_login = rs.getString(rs.getColumnIndex(DBHelper.c_login));
AsyncTaskRunner taskRunner = new AsyncTaskRunner();
taskRunner.execute(c_login);
lvMarkets.setAdapter(jAdapter);
return rootView;
}
private class AsyncTaskRunner extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params)
{
final String fin_login=params[0];
StringRequest stringRequest = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
Log.d(debug,response);
try
{
jsonArray =new JSONArray(response);
jAdapter= new JsonAdapter(getActivity(),jsonArray,login);
}
catch (JSONException e)
{
Log.d(debug,e.toString());
}
}
}, new Response.ErrorListener()
{
public void onErrorResponse(VolleyError error)
{
Log.d(debug,error.toString());
}
}){
#Override
protected Map<String,String>getParams()
{
Map<String,String> params=new HashMap<String,String>();
params.put("c_login",fin_login);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(stringRequest);
return fin_login;
}
}
Hope someone could point out what went wrong with my code and someone could also point out on how to fetch data on online much more faster.
Thanks...
Try this:
private void parsingValues() {
URL obj = null;
HttpURLConnection con = null;
String USER_AGENT = "Mozilla/5.0";
try {
//parameter to post
String POST_PARAMS = "deviceos=" + deveiceOs + "&devicetype=" + deviceType +"&deviceid=" ;
obj = new URL("Your URI");
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//getResponse
String subsResponse = response.toString();
final JSONObject responsesubs = new JSONObject(subsResponse);
//Here your parsing process
}
}
});
} else {
System.out.println("POST request not worked");
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Call this method to your doinbackground of Asynhronous Task(parsingValues())
I'm just starting to develop android application and want to try to connect to my router. Wrote application using Jackson, but get stuck with json request for login to the router. IP of my router is 192.168.1.1 and username and password should be taken from EditText fields.
android.os.NetworkOnMainThreadException
There is json string for login:
{ "jsonrpc": "2.0", "id": 1, "method": "call", "params": [ "00000000000000000000000000000000", "session",
"login", { "username": "root", "password": "admin01" } ] }
This is my RestRequest.java
public class RestRequest {
private static final String TAG = JacksonUtil.class.getSimpleName();
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public RestRequest(){
}
public String makeWebServiceCall(String url, int requestmethod){
return this.makeWebServiceCall(url, requestmethod, null);
}
public String makeWebServiceCall(String urladdress, int requestmethod, HashMap<String, String> params){
URL url;
String responce = "";
try {
url = new URL(urladdress);
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setReadTimeout(15000);
urlconnection.setConnectTimeout(15000);
urlconnection.setDoInput(true);
urlconnection.setDoOutput(true);
if(requestmethod == POST){
urlconnection.setRequestMethod("POST");
}else if(requestmethod == GET){
urlconnection.setRequestMethod("GET");
}
if(params != null){
OutputStream outputstream = urlconnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputstream, "UTF-8"));
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
bufferedWriter.write(result.toString());
bufferedWriter.flush();
bufferedWriter.close();
outputstream.close();
}
int responceCode = urlconnection.getResponseCode();
if(responceCode == HttpsURLConnection.HTTP_OK){
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
while ((line = br.readLine()) != null){
responce += line;
}
}else {
responce = "";
}
} catch (Exception e){
Log.e(TAG, "IOException parsing to json", e);
}
return response;
}
Edited my LoginActivity.java
Can anyone to look at this activity and tell what I'm doing wrong
public class LoginActivity extends AppCompatActivity {
private String page_url = "http://192.168.1.1/ubus";
#Bind(R.id.user_name_edit_text)
TextView user_name;
#Bind(R.id.user_password_edit_text)
TextView user_password;
#Bind(R.id.login_button)
Button login_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = page_url;
String username = getUserName();
String password = getPassword();
TryToLogin tryToLogin = new TryToLogin();
tryToLogin.execute(url, username, password);
}
});
class TryToLogin extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
URL url = null;
try {
url = new URL(page_url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String getUserName() {
String username = user_name.getText().toString();
return username;
}
private String getPassword() {
String password = user_password.getText().toString();
return password;
}
You cannot make network calls using the main thread in Android - this is by design to ensure the UI thread remains responsive and does not wait. You need to perform this call in an AsyncThread or normal Thread