添加标题以在字符串中发布请求

时间:2017-12-01 12:25:26

标签: android post header

我正在使用该代码发送POST请求。

现在我需要为此添加标题,任何方法吗? 在Google中,大多数方法是使用其他方法,如HttpPost和addHeader方法。

try {
        System.out.println("FirebaseInstanceId.getInstance().getToken()" + token);

        //String data = URLEncoder.encode("?api-fcm=register", "UTF-8");

        String data = URLEncoder.encode("regid", "UTF-8")
                + "=" + URLEncoder.encode(FirebaseInstanceId.getInstance().getToken(), "UTF-8");

        if ( ContextCompat.checkSelfPermission( this, Manifest.permission.READ_PHONE_STATE ) == PackageManager.PERMISSION_GRANTED ) {
            data += "&" + URLEncoder.encode("serial", "UTF-8") + "=" + URLEncoder.encode( Build.SERIAL, "UTF-8");
        }

        data += "&" + URLEncoder.encode("device_name", "UTF-8")
                + "=" + URLEncoder.encode(getDeviceName(), "UTF-8");


        data += "&" + URLEncoder.encode("os_version", "UTF-8")
                + "=" + URLEncoder.encode(getAndroidVersion(), "UTF-8");

        String text = "";
        BufferedReader reader = null;

        try {
            URL url = new URL("http://somelink");

            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

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

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            text = sb.toString();
        } catch (Exception ex) {

1 个答案:

答案 0 :(得分:2)

这样的代码:

  HttpUrlConnection myURLConnection = (HttpUrlConnection)conn;
  myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
  myURLConnection.setRequestProperty("Content-Language", "en-US");

在行之后添加:

  URLConnection conn = url.openConnection();

这里的“Content-Type”,“Content-Length”,“Content-Language”是标题。

谢谢,如果需要更多,请告诉我。

快乐编码!!

相关问题