java Android HttpUrlConnection 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28561076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:50:06  来源:igfitidea点击:

Android HttpUrlConnection not working

javaandroidhttpclienthttpurlconnection

提问by anonymousCoder

Basically, I'm trying to connect to a web interface through an Android App.

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

I managed to send commands to the form successfully using HttpClient. However, I want to accomplish this using HttpUrlConnection as recommended here http://android-developers.blogspot.com/2011/09/androids-http-clients.htmlwith the intention of having a faster and more energy efficient connection.

我设法使用 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();

Edit: No exceptions are being thrown since the code is executing just fine, the request is just probably not in the expected format by the server?

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

回答by anonymousCoder

connnection.getInputStream() was required for the POST to work. Fixed.

POST 需要 connnection.getInputStream() 才能工作。固定的。

回答by Xinjian Yao

Just add one line

只需添加一行

connection.getRequestMethod();

and it will work.

它会起作用。

I dont know why but this works for me after I have spent a whole day on it!

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

回答by faljbour

Here is what I use to send http requests using HttpURLConnection, notice that the connection.connect() is right after setting up the HttpURLConnection not at the end, also the setDoInput makes the request POST instead of the default get,

这是我用来使用 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);

回答by sockeqwe

Could you provide more information, like Exceptions, or the servers response? Does the server receives a your request?

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

However, I recommend you to use okhttpwhich has been build on top of HttpUrlConnection

但是,我建议您使用okhttp,它已经建立在HttpUrlConnection

回答by Chetan Panchal

To share Data using HttpUrlConnection class Here is Simple Connection class this Will Help you to Connect With WS , and to pass data using JSON parsing ..

使用 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;
    }
}

To use this class i use the Asyn class Like,...

要使用这个类,我使用 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();
                }
            }
    }

回答by Tushar Mate

In my case, it was actually NetworkOnMainThreadException thrown but not shown clearly in Logs

就我而言,它实际上是抛出了 NetworkOnMainThreadException 但在日志中没有清楚地显示