首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android POST httpsurlconnection

Android POST httpsurlconnection
EN

Stack Overflow用户
提问于 2017-04-21 00:32:49
回答 1查看 88关注 0票数 1

我在通过HttpsUrlConnection发送POST请求时遇到问题。当我不使用DataOutputStream的时候,一切都很好。在此之后,应用程序不会写入日志。我认为问题在于为POST创建数据,或者在连接所需属性的设置中,或者在发送数据的方法中。我的类看起来像这样

代码语言:javascript
复制
public class Connection extends AsyncTask<String, Void, Object> {

private List<String> cookies = new ArrayList<String>();

@Override
protected Object doInBackground(String... strings) {
    Log.d("Background", "working in background");
    CookieHandler.setDefault(new CookieManager());
    String result = "";
    String  urlParameters = "formname="+FORMNAME+"&default_fun="+DEFAULT_FUN+"&userid="+strings[1]+"&password="+strings[2];
    byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
    try {
        result = getPageContent(strings[0]);
        getsid(result);
        Log.d("sid", sid);
        Log.d("urlParameters", urlParameters);
        sendPost(strings[0]+"index.php?"+sid, postData);
        result = getPageContent(strings[0]+"logged_inc.php?"+sid+"&t=6799847");
        Log.d("After post", result);
    }catch(Exception e) {

    }

    return null;
}

private String getPageContent(String page) throws Exception{
    String result = "";
    Log.d("getPageContent ", page);
    URL url = new URL(page);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    trustEveryone();
    conn.setSSLSocketFactory(sc.getSocketFactory());
    Log.d("result", result);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Connection", CONNECTION);
    conn.setRequestProperty("Content-Type", CONTENT_TYPE);
    conn.setRequestProperty("User-Agent",USER_AGENT);
    conn.connect();
    result = readContent(conn.getInputStream());


    return result;
}
private static void sendPost(String page, byte[] postData) throws Exception {

    Log.d("postPageContent ", page);
    URL url;
    int postLength = postData.length;
    HttpsURLConnection urlConnection = null;
    url = new URL(page);
    urlConnection = (HttpsURLConnection) url.openConnection();
    trustEveryone();

    urlConnection.setSSLSocketFactory(sc.getSocketFactory());
    urlConnection.setUseCaches(false);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("User-agent", "Mozilla/5.0");
    urlConnection.setRequestProperty("HOST", "host.com");
    urlConnection.setRequestProperty("Connection", "keep-alive");
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.connect();
    int responseCode = urlConnection.getResponseCode();
    Log.d("response code", responseCode+"");
    // Send post request
    DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
    wr.write(postData);
    wr.flush();
    wr.close();
}

private void getsid(String html) {...}

private static void trustEveryone() {

    TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {};
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {};
            }
    };

    try {
        sc  = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private  static String readContent(InputStream is) throws  Exception{...}

}

EN

回答 1

Stack Overflow用户

发布于 2018-03-08 17:06:38

我认为你不需要dataOutputStrem。相反,您应该使用OutputStreamWriter来写入数据。

希望这能解决你的问题。

代码语言:javascript
复制
URL url = new URL(Url+"ApiController");
        HttpURLConnection client = (HttpURLConnection) url.openConnection();
        client.setRequestMethod("POST");
        client.setRequestProperty("Content-Type", "application/json");
        client.setRequestProperty("Authorization",
                "Basic xxxxxxxx");

        client.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(client.getOutputStream());
        String data = "2";
        wr.write( data );
        wr.flush();

        // Get the server response

        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            // Append server response in string
            sb.append(line + "\n");
        }

        String result = sb.toString();
        array = new JSONArray(result);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43525102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档