当前位置: 首页 > 知识库问答 >
问题:

android api 23中带有httpurlconnection的Java rest api

谢和颂
2023-03-14

我用java创建了一个webservice

@path(“/app”)公共类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());
}

}

此方法的URL为:http://localhost:8080/webapi/api/app/login“,

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

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个答案

岳硕
2023-03-14

请像这样修改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"));
        }
 类似资料:
  • 我的问题是关于应该在Android中使用HttpURLConnection编写的代码来获得响应? 请求和2个答复如下:

  • 我在docker-compose文件中定义了两个容器: 现在,我想通过HTTPURLConnection从Java Web应用程序内部访问URL。 问题:返回400错误 代码是这样的(当我尝试通过curl连接到URL时,标题几乎是相同的--这在容器中起作用哈): -工作-将不工作,但不会出现404错误

  • 问题内容: 我有一个Java应用程序(JDK 1.7.0_13),正在使用java.net.HttpURLConnection连接到一些进行会话管理的基于servlet的服务。我试图弄清楚如何使用java.net.CookieManager跟踪会话cookie。阅读文档后,我得到的印象是,使用CookieHandler.setDefault(new CookieManager())安装Cookie

  • 问题内容: 我正在尝试编写一个Java程序,该程序将自动下载并命名一些我最喜欢的网络漫画。由于我将请求来自同一域的多个对象,因此我希望有一个持久的http连接,在下载所有漫画之前,我可以一直保持打开状态。以下是我正在进行的工作。如何在不打开新的http连接的情况下从相同域但路径不同发出另一个请求? 问题答案: 根据此处的文档,HTTP持久性在Java中是透明处理的,尽管它提供了一些选项,也可以通过

  • 我正在尝试使用HttpUrlConnection POST方法使用multipart上传文件。文件上传正确,我收到了响应。但是当我跟踪进度时,它只是在1秒内给出所有进度,即使是文件。 这是我上传文件的代码: 任何帮助或解释,真的非常感谢。

  • 我试图用PUT请求调用REST API,但收到400个错误代码(错误请求)。有人能看出我做错了什么吗? 我已经用REST客户端成功调用了这个API,下面是使用的头和主体: https://imgur.com/dZVyawnhttps://imgur.com/lMtn2JB 错误400收到错误请求响应