单击按钮android studio发布请求

时间:2017-04-12 10:53:59

标签: java android

我正在为Phillips Hue Lights创建一个应用程序,我希望能够单击一个按钮,该按钮将从我的应用程序发出请求到Hue Bridge的特定URL以获取用户名返回。

我的代码:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.concurrent.ExecutionException;

public class Device extends AppCompatActivity {

HashMap<String, String> params = new HashMap<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_device);
    {

        params.put("devicetype", "final_year_project#michelle");

        PostHandler handler = new PostHandler(params);
        try {
            JSONObject response = handler.execute("http://192.168.1.85/api/").get();

            Log.d("TEST_RESPONSE", response.toString());

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
}

我还创建了PostHandler类:

import android.os.AsyncTask;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PostHandler extends AsyncTask<String, Void, JSONObject> {

OkHttpClient client = new OkHttpClient();
HashMap<String, String> params = new HashMap<>();

public PostHandler(HashMap params) {
    this.params = params;
}

public PostHandler() {

}

@Override
protected JSONObject doInBackground(String... url) {

    client = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.MINUTES)
            .writeTimeout(5, TimeUnit.MINUTES)
            .readTimeout(5, TimeUnit.MINUTES)
            .build();

    FormBody.Builder body = new FormBody.Builder();

    for ( Map.Entry<String, String> entry : params.entrySet() ) {
        body.add( entry.getKey(), entry.getValue() );
    }

    RequestBody formBody = body.build();

    Request request = new Request.Builder()
            .url(url[0])
            .post(formBody)
            .build();

    try{
        Response response = client.newCall(request).execute();
        String result = response.body().string();
        JSONObject json = new JSONObject(result);
        return json;
    }catch (Exception e){
        e.printStackTrace();
    }

    return null;
}

}

我收到错误&#34;无法解决符号参数&#34;并且邮寄请求不起作用。

有谁知道我哪里出错了?我是API的新手。

1 个答案:

答案 0 :(得分:0)

setContentView(R.layout.activity_device);之后添加以下行:

ContentValues params = new ContentValues();

您尚未在代码中的任何位置声明变量params