如何使用 HttpURLConnection 发布数据

Posted

技术标签:

【中文标题】如何使用 HttpURLConnection 发布数据【英文标题】:How to post data using HttpURLConnection 【发布时间】:2016-04-11 00:56:08 【问题描述】:

我从 API23 更改为 22,因为他们说 httpclient 不可用。当我切换到 API22 时,我遇到了 HttpClient、HttpPost 和 NameValuePair 的问题。我找到了使用 HttpURLConnectionHandler 的解决方案。但我不知道如何将其用于以下方法。

 public void send(View v)


    HttpClient httpclient = new DefaultHttpClient();
    // put the address to your server and receiver file here
    HttpPost httppost = new HttpPost("http://yoursite/yourphpScript.php");
    try 
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        // we wont be receiving the parameter ID in your server, but it is here to show you how you can send more data
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        // message is the parameter we are receiving, it has the value of 1 which is the value that will be sent from your server to your Arduino board
        nameValuePairs.add(new BasicNameValuePair("message", "1"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpclient.execute(httppost); // send the parameter to the server
     catch (ClientProtocolException e) 
        // TODO Auto-generated catch block
     catch (IOException e) 
        // TODO Auto-generated catch block
    

谁来帮帮我

【问题讨论】:

您到底想做什么,您遇到的具体问题是什么? (您收到了哪些错误消息。) HttpPost、HttpClient 和 NameValuePair 已弃用。我需要将此 post 方法与我已经拥有的 HttpURLConnectionHandler 类一起使用@ChrisBritt 【参考方案1】:

你可以这样做:

public boolean sendPost(MessageSenderContent content) 

        HttpURLConnection connection;
        try 
            URL gcmAPI = new URL("your_url");
            connection = (HttpURLConnection) gcmAPI.openConnection();

            connection.setRequestMethod("POST");// type of request
            connection.setRequestProperty("Content-Type", "application/json");//some header you want to add
            connection.setRequestProperty("Authorization", "key=" + AppConfig.API_KEY);//some header you want to add
            connection.setDoOutput(true);

            ObjectMapper mapper = new ObjectMapper();
            mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
            DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
            //content is the object you want to send, use instead of NameValuesPair
            mapper.writeValue(dataOutputStream, content);

            dataOutputStream.flush();
            dataOutputStream.close();

            responseCode = connection.getResponseCode();
         catch (IOException e) 
            e.printStackTrace();
        
        if (responseCode == 200) 
            Log.i("Request Status", "This is success response status from server: " + responseCode);
            return true;
         else 
            Log.i("Request Status", "This is failure response status from server: " + responseCode);
            return false;
        

MessageSenderContent 的示例,您可以为“message”和“id”创建自己的示例:

public class MessageSenderContent implements Serializable 
    private List<String> registration_ids;
    private Map<String, String> data;

    public void addRegId(String regId)
        if (registration_ids==null)
            registration_ids = new LinkedList<>();
            registration_ids.add(regId);
        
    

    public void createData(String title,String message) 
        if (data == null)
            data = new HashMap<>();

        data.put("title", title);
        data.put("message", message);
    

    public Map<String, String> getData() 
        return data;
    

    public void setData(Map<String, String> data) 
        this.data = data;
    

    public List<String> getRegIds() 
        return registration_ids;
    

    public void setRegIds(List<String> regIds) 
        this.registration_ids = regIds;
    

    @Override
    public String toString() 
        return "MessageSenderContent" +
                "registration_ids=" + registration_ids +
                ", data=" + data +
                '';
    

更新

你可以在你的 build.gradle 文件中导入之后使用 HttpUrlConnection

android 
    compileSdkVersion 23
    buildToolsVersion "23.0.0"
    useLibrary 'org.apache.http.legacy' // this one will let you use HttpUrlConnection
    packagingOptions 
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'

    ...

【讨论】:

非常感谢!但是我也可以得到你使用的 HttpURLConnection 类吗? 它说“警告:无法找到可选库:org.apache.http.legacy”。并且无法解析 setRequestmethod、setRequestProperty 方法 无法解析,因为您尚未成功导入该库。我更新了我的答案,另外,你可以看看这个:***.com/questions/30856785/… 更新没意义,HttpUrlConnection 跟遗留的 Apache 东西没关系

以上是关于如何使用 HttpURLConnection 发布数据的主要内容,如果未能解决你的问题,请参考以下文章

使用 HTTPUrlConnection 时如何保留 cookie?

如何从 HttpURLConnection 实例获取 HTTP 请求字符串

如何修改 HttpUrlConnection 的标头

如何从 HttpURLConnection 读取 json 数据

如何使用 HttpURLConnection 在 php 中发送 json 以读取像“php://input”?

如何在Android Studio中使用Java的应用程序后台执行HttpURLConnection之类的任务?