HTTPS发布请求,从HTML到Java

时间:2015-06-27 00:05:19

标签: java android httpurlconnection html-post

我想"翻译"此HTML请求发布到Android

<form name="myForm" action="https://mysite.example" method="POST">
  <input type="hidden" name="Key1" value=1>
  <input type="hidden" name="Key2" value="2">
  <input type="hidden" name="Key3" value="3">
</form>

请注意,第一个值是整数,而不是字符串。

所以我尝试使用stackoverflow上的代码:

public String  performPostCall(String requestURL, HashMap<String, String> postDataParams) {
    URL url;
    String response = "";
    try {
        url = new URL(requestURL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));

        writer.flush();
        writer.close();
        os.close();
        int responseCode=conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
        }
        else {
            response="";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}

在我的AsyncTask中,我正在做:

HashMap<String, String> parameters = new HashMap<>();
String url = "https://mysite.example";
String result;

parameters.put("Key1", "1");
parameters.put("Key2", "2");
parameters.put("Key3", "3");
result = performPostCall(url, parameters);

但这不起作用。怎么了?

2 个答案:

答案 0 :(得分:0)

我认为你错过了一条重要的线路,它在输出流之前建立了实际连接

conn.connect();

您还需要在AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.INTERNET"/> 

答案 1 :(得分:0)

你正在关闭&#34;作家&#34;在它处理之前:

writer.flush();
writer.close();
os.close();

int responseCode = conn.getResponseCode();