首页 > 解决方案 > 如何将带有 Java (Android Studio) 中的值的 HTTP Post 请求发送到 Ubidots

问题描述

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

//这是我的代码。我正在尝试向 Ubidots 发出 HTTP 发布请求。如何将带有Java(Android Studio)中的值的HTTP Post请求发送到Ubidots?

class soll{
         protected void doInBackground(String... params) {
            String urlString = params[0]; // URL to call
            String data = params[1]; //data to post
            OutputStream out = null;

            try {
                URL url = new URL(urlString);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setDoInput(true);
                urlConnection.setReadTimeout(10000);
                urlConnection.setConnectTimeout(15000);
                out = new BufferedOutputStream(urlConnection.getOutputStream());

                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                writer.write(data);
                writer.flush();
                writer.close();
                out.close();

                urlConnection.connect();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

public class CallAPII{
    public static void main(String[] args) {
        soll obj = new soll();
        obj.doInBackground("http://things.ubidots.com/api/v1.6/","{\"value\":\"1\"}");
    }
}

//这是我的代码,我无法找出错误

标签: javaandroid

解决方案


下面的代码应该可以解决问题

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package httpexample;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jose garcia
 */
public class HttpExample {

    /**
     * @param args the command line arguments
     * @throws java.net.MalformedURLException
     */

    private static String deviceLabel = "my-device";
    private static String variableLabel = "my-variable";
    private static String token = "";
    private static String endpoint = "https://industrial.api.ubidots.com/api/v1.6/devices";
    private static String userAgent = "Java/0.1";

    public static void main(String[] args) throws MalformedURLException, IOException {
        String ubiEndpoint= endpoint + "/" + deviceLabel;
        String testValue = "1";
        URL ubiUrl = new URL(ubiEndpoint);
        String json = "{\"" + variableLabel + "\":" + testValue + "}";

        System.out.println("payload: " + json);

        HttpURLConnection con = (HttpURLConnection) ubiUrl.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", userAgent);
        con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        con.setRequestProperty("X-AUTH-TOKEN", token);
        con.setDoOutput(true);
        con.setDoInput(true);

        try {
            con.setRequestMethod("POST");
            try (OutputStream os = con.getOutputStream()) {
                os.write(json.getBytes("UTF-8"));
            }
            int responseCode = con.getResponseCode();
            System.out.println("response code: " + responseCode);
        } catch (ProtocolException ex) {
            Logger.getLogger(HttpExample.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

推荐阅读