将标题添加到字符串中的发布请求 [英] Add header to post request in string

查看:85
本文介绍了将标题添加到字符串中的发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using that code to send POST requests.

现在我需要为此添加标题,有什么方法吗? 在Google中,大多数方法是使用其他方法,例如HttpPost和addHeader方法.

Now i need to add header to this, any ways of doing it? In Google most ways is to use another methods, like HttpPost and addHeader method.

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) {

推荐答案

执行以下代码:

  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"都是标题.

and here "Content-Type", "Content-Length", "Content-Language" are headers here.

谢谢,让我知道是否需要更多.

Thanks and let me know if need more.

快乐编码!

这篇关于将标题添加到字符串中的发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆