如何减少HTTPURLConnection代码

时间:2018-02-13 10:58:33

标签: android

解决: 我已经继续使用Retrofit库的推荐,它减少了我的代码分配。感谢您的帮助。

我有一个Android应用程序,在页面上我有代码显示在下面当有人点击一个开关它将使用PUT将数据作为JSON发送到服务器。但是,我不知道如何以一种我可以再次使用它的方式减少此代码。我不想要保持复制和粘贴相同的代码并更改requestMethod或我写的字节类型。

这是我的oncreate中的代码,当开关打开时,它将执行图B中所示的操作。我想在开关关闭时将其删除而不必复制图B中的相同代码并更改它然后执行它。:

test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean on = ((Switch) v).isChecked();
            if(on)
            {
                //Do something when switch is on/checked
                new RetrieveFeedTask().execute();
                new newtask().execute();

            }
            else
            {
                //Do something when switch is off/unchecked

            }
        }
    });

图B

class RetrieveFeedTask extends AsyncTask<String, String, String> {

 private Exception exception;


 protected String doInBackground(String... urls) {

 URL url = null;
 try {
     String strUrl = "http://192.168.0.104:5053/TEST";
     url = new URL(strUrl);
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();

     connection.setRequestMethod("POST");
     connection.setRequestProperty("Content-Type", "application/json; charset");
     connection.setDoInput(true);
     connection.setDoOutput(true);

     OutputStream stream = connection.getOutputStream();
     DataOutputStream writer = new DataOutputStream(stream);
     connection.connect();
     //Log.d("WARN", "TEST");
     // The LogCat prints out data like:
     // ID:test,Email:test@gmail.com,Pwd:test
    String suuid = UUID.randomUUID().toString();

     writer.writeBytes("{\"id\" : \""+suuid+ "\", \"sensorType\" : \"sound\", \"threshold\" : \"50\", \"operator\" : \">\", \"actuator\" : \"1\", \"actuatorAction\" : \"4\"}");
     writer.flush();
     writer.close();

     InputStream response = connection.getInputStream();
     StringBuilder sb = new StringBuilder();
     BufferedReader bf = new BufferedReader(new InputStreamReader(response, "utf-8"));
     String responseLine = bf.readLine();
     while(responseLine != null) {
         sb.append(responseLine);
         responseLine = bf.readLine();
     }

     stream.close();
     System.out.println("executed");
     connection.disconnect();



 } catch (IOException e) {
     e.printStackTrace();
 }
 return "fff";
 }

 protected String onPostExecute() {
 // TODO: check this.exception
 // TODO: do something with the feed
 return "ASDASD";
 }



 }

如果需要更多信息,请告知我们。

4 个答案:

答案 0 :(得分:2)

使用Android Asynchronous Http Client

示例代码:

AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("key", "value");
params.put("more", "data");
client.post("https://www.google.com", params, new AsyncHttpResponseHandler() {

    @Override
    public void onStart() {
        // called before request is started
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // called when response HTTP status is "200 OK"
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
    }

    @Override
    public void onRetry(int retryNo) {
        // called when request is retried
    }
});

<强>摇篮:

dependencies {
  compile 'com.loopj.android:android-async-http:1.4.9'
}

答案 1 :(得分:0)

您可以使用非常轻量级的Ion库。用法示例在Github上:https://github.com/koush/ion

答案 2 :(得分:0)

<强> Android的排球(废弃):   https://github.com/mcxiaoke/android-volley      或

<强>改造:

  • 类型安全的HTTP客户端
  • 在易用性,性能,捕获,可扩展性,分段上传和其他方面,Retrofit绝对是排球的更好选择。它是一个类型安全的REST客户端 (http://square.github.io/retrofit

答案 3 :(得分:0)

首先,我建议使用网络库(Retrofit,Volly等),因为直接处理http连接有点复杂,并且容易出现库已经解决的错误。

但是如果您仍然希望直接使用http连接,您可以创建一个扩展异步任务的httpConnection任务,并在创建时获得必要的参数。

例如 -

public class HttpConnection extends AsyncTask<String, String, String> {

private final String mBytes;
private final String mMethod;

public HttpConnection(String method, String bytes) {
    mMethod = method;
    mBytes = bytes;
}

@Override
protected String doInBackground(String... strings) {

    // ... open connection
    writer.writeBytes(mBytes);
    return null;
}

显然,您可以将其更改为使用您想要/需要的任何参数