【问题标题】:Android HttpUrlConnection not workingAndroid HttpUrlConnection 不起作用
【发布时间】:2015-02-17 12:06:36
【问题描述】:

基本上,我正在尝试通过 Android 应用程序连接到网络界面。

我设法使用 HttpClient 成功地将命令发送到表单。但是,我想按照此处http://android-developers.blogspot.com/2011/09/androids-http-clients.html 的建议使用 HttpUrlConnection 来完成此操作,以实现更快、更节能的连接。

URL url = new URL("http://" + mIpAddress + ":" + mPort + "/command.html");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);

OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(URLEncoder.encode("parameter=" + value, "UTF-8");
writer.flush();
writer.close();
os.close();

connection.connect();

编辑:没有抛出异常,因为代码执行得很好,请求可能不是服务器预期的格式?

【问题讨论】:

  • 您好,我正在使用 28 以上的 URLconnection,但导入这些库时显示错误,您有什么答案吗?是的,它现在正在工作,但显示错误导入原因

标签: java android httpclient httpurlconnection


【解决方案1】:

connnection.getInputStream() 是 POST 工作所必需的。固定。

【讨论】:

  • 它给了我一个例外,FileNotFoundException
  • 哇。两个小时以来,我一直陷入同样的​​问题。这有助于
【解决方案2】:

这是我用来使用 HttpURLConnection 发送 http 请求的方法,请注意 connection.connect() 是在设置 HttpURLConnection 之后而不是最后,setDoInput 也使请求 POST 而不是默认的 get,

    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    //conn.setReadTimeout(10000 /* milliseconds */);
    // conn.setConnectTimeout(15000 /* milliseconds */);
    //conn.setRequestMethod("GET");
    //conn.setDoInput(true);   //* uses POST
    // Starts the query
    conn.connect();
    InputStream stream = conn.getInputStream();
    //String data = convertStreamToString(stream);
    int sz = stream.available();
    byte[] b = new byte[sz];
    stream.read(b);
    stream.close();
    String data = new String(b);

【讨论】:

  • 我刚刚尝试过连接,按照你的例子,但是服务器仍然没有得到我的命令或没有正确得到它。
  • 你能把 commad.html 中的内容贴出来吗?我提供的代码在工作应用程序中使用,并且在提供有效 url 时可以正常工作。
【解决方案3】:

只需添加一行

connection.getRequestMethod();

它会起作用的。

我不知道为什么,但是在我花了一整天的时间后,这对我有用!

【讨论】:

    【解决方案4】:

    您能否提供更多信息,例如异常或服务器响应?服务器收到你的请求了吗?

    但是,我建议您使用在HttpUrlConnection 之上构建的okhttp

    【讨论】:

    • 据我所知,我没有收到任何异常,也没有任何回应。服务器/站点不必发回响应,对吗?我现在试图避免使用第三方库,因为我只需要一个简单的连接方法。但是如果一切都失败了,我会考虑使用 okhttp,谢谢你告诉我!无论如何,我能做些什么来提供更好的信息吗?真的不知道要调试什么,因为连接到服务器似乎是一个试错过程。
    • 您是在自己的线程还是异步任务中运行您的 http 代码?由于 android 4.0 android 不会让你执行阻塞主 ui 线程以进行长时间运行的事情,例如 http 调用。通常在这种情况下会抛出异常,但可能由于某种原因在您的测试设备上没有这样做......
    • 我在 AsyncTask 中正确运行它。基本上,我在这个类中有两种方法。一种使用 HttpClient(我认为是 Apache),另一种使用 HttpUrlConnection。 HttpClient 工作正常,所以线程没有问题,但是 HttpUrlConnection 给了我问题。这是我第一次在 Java 中使用网络,所以对于上述实现我可能遗漏了一些非常简单的东西......我还尝试比较 HttpClient 和 HttpUrlConnection 之间的字符编码等,但我没有看到任何差异。
    【解决方案5】:

    使用 HttpUrlConnection 类共享数据 这是 Simple Connection 类,它将帮助您与 WS 连接,并使用 JSON 解析传递数据..

    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class CommonConnectionClass {
        JSONObject jsonObject;
        public JSONObject getConnection(String u,JSONObject object){
            try {
    
                //URL url=new URL("https://e-gurukulam.000webhostapp.com/public_html/project/login.php"+u+".php");
                URL url=new URL("http://"+new Connection_Url_Setter().urlIp+"/classroom/"+u+".php");
               // URL url=new URL("http://192.168.43.120/classroom/"+u+".php");
                HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setRequestProperty("Content-Type","application/json; charset=utf-8");
                httpURLConnection.setRequestProperty("Accept","application/json; charset=utf-8");
                httpURLConnection.setDoInput(true);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.connect();
    
                if(object!=null) {
                    DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
                    dataOutputStream.write(object.toString().getBytes());
    
                }
                int code=httpURLConnection.getResponseCode();
                if(code== HttpURLConnection.HTTP_OK){
                    String inputLine;
                    StringBuilder stringBuilder=new StringBuilder();
    
    
                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                    while((inputLine=bufferedReader.readLine())!=null){
                        stringBuilder.append(inputLine);
                    }
                    jsonObject=new JSONObject(stringBuilder.toString());
                }
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
    
            return jsonObject;
        }
    }
    

    要使用这个类,我使用 Asyn 类 Like,...

    class userNameFetchTask extends AsyncTask<Void, Void, JSONObject> {
                JSONObject object, jsonObject, json;
                JSONArray jsonArray;
                ArrayList<CreateGroupModel> lidList = new ArrayList<>();
                String lid, name;
    
                @Override
                protected void onPreExecute() {
                    jsonObject = new JSONObject();
                    try {
                        jsonObject.put("lid", sp.getString("lid", null));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    super.onPreExecute();
                }
    
                @Override
                protected JSONObject doInBackground(Void... voids) {
                    object = new JSONObject();
                    CommonConnectionClass commonConnectionClass = new CommonConnectionClass();
                    object = commonConnectionClass.getConnection("selectUserForGroup", jsonObject);
                    return object;
                }
    
                @Override
                protected void onPostExecute(JSONObject jsonObject) {
                    super.onPostExecute(jsonObject);
                    jsonArray = new JSONArray();
                    try {
                        jsonArray = jsonObject.getJSONArray("response");
                        for (int i = 0; i < jsonArray.length(); i++) {
    
                            CreateGroupModel model = new CreateGroupModel();
    
                            json = jsonArray.getJSONObject(i);
                            model.setLid(json.getString("relative_lid"));
                            model.setName(json.getString("name"));
                            model.setEmail(json.getString("email"));
                            model.setImage(json.getString("image"));
    
                            lidList.add(model);
                        }
                        viewstudentsadapterForCreateGroup viewstudentsadapterForCreateGroup = new viewstudentsadapterForCreateGroup(getApplicationContext(), lidList, createGroup_Activity.this);
                        listView.setAdapter(viewstudentsadapterForCreateGroup);
    
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
        }
    

    【讨论】:

      【解决方案6】:

      在我的例子中,它实际上是抛出 ​​NetworkOnMainThreadException 但在日志中没有清楚地显示

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-19
        • 1970-01-01
        • 2017-10-25
        • 1970-01-01
        • 2016-06-29
        • 1970-01-01
        相关资源
        最近更新 更多