我可以在Android中使用POST方法从URL获取数据吗?

时间:2019-06-06 10:46:21

标签: java android

我想使用POST方法从URL提取数据。我已经使用GET方法获取了数据。现在,我想使用POST方法。当我单击按钮时,即使我提供了Internet许可,也没有任何响应。我认为还有其他问题。

我曾尝试搜索许多站点并观看教程,但是我所获得的只是如何使用POST方法将数据发送到服务器。

MainActivity.java

externalNativeBuild {
            cmake {
               // cppFlags ""
                version "3.81"
            }
        }

Async.java

package com.example.apipostmethod;

import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    public String data="";
    public TextView response;
    public Button btn;

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

        if (android.os.Build.VERSION.SDK_INT > 15) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        response = findViewById(R.id.textView);
        btn = findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Async().execute();
            }
        });
        data = Async.data();
        Toast.makeText(getApplicationContext(),data,Toast.LENGTH_LONG).show();
        response.setText(data);
    }
}

activity_main.xml

package com.example.apipostmethod;

import android.os.AsyncTask;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

public class Async extends AsyncTask {

    public String URLine = "https://api.myjson.com/bins/uizi7";
    public static String result="";
    @Override
    protected Object doInBackground(Object[] objects) {
        try {
            URL url = new URL(URLine);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.connect();

            Scanner sc = new Scanner(url.openStream());
            while(sc.hasNext())
            {
                result+=sc.nextLine();
            }

        }

        catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String data(){

        return result;
        }
}

我在logcat中连续不断收到此错误,次数不受限制。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical"
    tools:context="com.example.apipostmethod.MainActivity">


    <Button
        android:id="@+id/button"
        android:layout_width="236dp"
        android:layout_height="57dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.496"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.898" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="347dp"
        android:layout_height="531dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="8dp"
        android:text="Response::"
        app:layout_constraintBottom_toTopOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>

我希望在textview中获取数据,但是我什至看不到用textview编写的文本。

1 个答案:

答案 0 :(得分:2)

使用HttpURLConnection将其用于POST请求,您可以根据需要添加或删除属性:

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(7000);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param1", paramValue1));
params.add(new BasicNameValuePair("param2", paramValue2));

OutputStream outputStream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
outputStream.close();

conn.connect();

这是getQuery()方法:

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}