2

I have created a webservice in java

@Path("/app") public class WebServiceApp {

MainClass mc = null; @Path("/login") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public User authenticateLoginWebService(Login log){ mc = new MainClass(); return mc.authenticateLogin(log.getUsername(), log.getPassword()); } 

}

This method has url: http://localhost:8080/webapi/api/app/login",

now to invoke this on android i have used following codes:

JSONParser:

public class JSONParser { String charset = "UTF-8"; HttpURLConnection conn; DataOutputStream wr; StringBuilder result; URL urlObj; JSONObject jObj = null; StringBuilder sbParams; String paramsString; public JSONObject makeHttpRequest(String url, String method, JSONObject params) { if (method.equals("POST")) { try { urlObj = new URL(url); conn = (HttpURLConnection) urlObj.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("content-type", "application/json"); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.connect(); OutputStream o = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(o, "UTF-8")); writer.write(params.toString()); writer.flush(); writer.close(); o.close(); ***Log.e("Req code", String.valueOf(conn.getResponseCode())); Log.e("Req Value", conn.getContent().toString())***; } catch (IOException e) { e.printStackTrace(); } } else if (method.equals("GET")) { try { urlObj = new URL(url); conn = (HttpURLConnection) urlObj.openConnection(); conn.setDoOutput(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept-Charset", charset); conn.setConnectTimeout(15000); conn.connect(); } catch (IOException e) { e.printStackTrace(); } } try { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); Log.e("Reader", reader.readLine()); StringBuilder result = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null){ result.append(line + "\n"); Log.e("Line", line); } reader.close(); Log.d("JSON Parser", "result: " + result.toString()); } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); try { jObj = new JSONObject(result.toString()); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } return jObj; } } 

LoginActivity:

public class LoginActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); final EditText username = (EditText) findViewById(R.id.username); final EditText password = (EditText) findViewById(R.id.password); TextView linkToSignup = (TextView) findViewById(R.id.linktosignup); linkToSignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it = new Intent(LoginActivity.this, SignUpActivity.class); startActivity(it); finish(); } }); Button login = (Button) findViewById(R.id.login_button); login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new HelperAsync().execute(username.getText().toString(), password.getText().toString()); } }); TextView mainMenu = (TextView) findViewById(R.id.mainMenu); mainMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it = new Intent(LoginActivity.this, HotelActivity.class); startActivity(it); finish(); } }); } public class HelperAsync extends AsyncTask<String, Void, User>{ @Override protected User doInBackground(String... params) { try { JSONObject inputParam = new JSONObject(); inputParam.put("username", params[0]); inputParam.put("password", params[1]); Log.e("inpt",inputParam.toString()); JSONObject obj = new JSONParser().makeHttpRequest("http://10.0.3.2:8080/webapi/api/app/login", "POST", inputParam); Log.e("jOsn", obj.toString()); if (obj != null) { try { String username = obj.getString("username"); int phoneNumber = obj.getInt("phoneNumber"); String role = obj.getString("role"); String name = obj.getString("name"); Log.e("username", username + " " + phoneNumber + " " + role + " " + name); } catch (JSONException e) { e.printStackTrace(); } } return null; } catch (JSONException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(User user) { super.onPostExecute(user); } @Override protected void onPreExecute() { super.onPreExecute(); } } } 

i am getting request code 415 with error message as Unsupported Media Type.

also stacktrace is as follow:

05-03 00:40:16.256 1252-1829/com.whiteboard.aajkamenu W/System.err: java.io.FileNotFoundException: http://10.0.3.2:8080/webapi/api/app/login 05-03 00:40:16.260 1252-1829/com.whiteboard.aajkamenu W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/System.err: at com.whiteboard.httpresource.JSONParser.makeHttpRequest(JSONParser.java:77) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/System.err: at com.whiteboard.aajkamenu.LoginActivity$HelperAsync.doInBackground(LoginActivity.java:71) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/System.err: at com.whiteboard.aajkamenu.LoginActivity$HelperAsync.doInBackground(LoginActivity.java:62) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/System.err: at java.lang.Thread.run(Thread.java:841) 05-03 00:40:16.264 1252-1829/com.whiteboard.aajkamenu W/dalvikvm: threadid=14: thread exiting with uncaught exception (group=0xa4d02b20) 05-03 00:40:16.272 1252-1829/com.whiteboard.aajkamenu E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3 Process: com.whiteboard.aajkamenu, PID: 1252 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.NullPointerException at com.whiteboard.httpresource.JSONParser.makeHttpRequest(JSONParser.java:91) at com.whiteboard.aajkamenu.LoginActivity$HelperAsync.doInBackground(LoginActivity.java:71) at com.whiteboard.aajkamenu.LoginActivity$HelperAsync.doInBackground(LoginActivity.java:62) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  at java.lang.Thread.run(Thread.java:841)  05-03 00:40:16.280 546-813/system_process W/ActivityManager: Force finishing activity com.whiteboard.aajkamenu/.LoginActivity 

how to resolve this error?

18
  • Why not using a Http Library as Retrofit it's well documented and easy to use. Commented May 2, 2016 at 16:40
  • If it is possible without using any library i would like to do it in that way. Any error u can found in this code? Commented May 2, 2016 at 16:47
  • Could you describe what's in line 91 of JSONParser? As we don't have line number in here. Commented May 2, 2016 at 16:51
  • That's the line no. 91: BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); Commented May 2, 2016 at 16:56
  • Ok, So probably it's not been able to reach the endpoint: http://localhost:8080/webapi/api/app/login try to test it with some tool like Postman to be sure that your been able to reach it. I think it isn't getting it cause of the java.io.FileNotFoundException: http://10.0.3.2:8080/webapi/api/app/login in the first line of your log. Commented May 2, 2016 at 17:06

1 Answer 1

1

Please modify your doInBackground code in HelperAsync like this:

@Override protected String doInBackground(String... args) { String login_url="http://localhost:8080/webapi/api/app/login"; try { URL ur = new URL(login_url); HttpURLConnection httpURLConnection = (HttpURLConnection) ur.openConnection(); OutputStream outputStream = httpURLConnection.getOutputStream(); httpURLConnection.setRequestMethod("POST"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>; nameValuePairs.add(new BasicNameValuePair("username, "Sarvesh")); nameValuePairs.add(new BasicNameValuePair("password", "12345")); } 
Sign up to request clarification or add additional context in comments.

4 Comments

you moved the code from jsonparser to mainactivity is there any benifir? and please provide the further steps! after creating list, what to do?
No,I am not moving your code anywhere,I am suggesting that you should send your post request like the above code.After the request on your postExecute Toast a message thar your Login is successfull.@Sarvesh
As per my knowledge NameValuePair are in apache.http package which is removed
There is a shortcut method,which I use you can use Retrofit 2 library.The library is very easy to use and works very fast. @Sarvesh

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.