Java api 23中的Java rest api与httpurlconnection

时间:2016-05-02 16:20:45

标签: java android web-services rest httpurlconnection

我在java中创建了一个web服务

@Path( “/应用程序”) 公共类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());
}

}

此方法包含网址:http://localhost:8080/webapi/api/app/login“,

现在在android上调用它我使用了以下代码:

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

我收到请求代码415,错误消息为Unsupported Media Type

stacktrace如下:

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

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

请修改HelperAsync中的doInBackground代码,如下所示:

@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"));
        }