Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了java-我可以在Android中使用POST方法从URL获取数据吗? 大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

@H_781_1@mainActivity.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);
    }
}

异步.java

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;
        }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://scheR_187_11845@as.android.com/apk/res/android"
    xmlns:app="http://scheR_187_11845@as.android.com/apk/res-auto"
    xmlns:tools="http://scheR_187_11845@as.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>

我连续不断地在logcat中收到此错误,例如无限次.

2019-06-06 16:03:48.315 1930-2875/? I/GnssLOCATIOnProvider: WakeLock acquired by sendmessage(REPORT_SV_STATUS,com.android.server.LOCATIOn.GnssLOCATIOnProvider$SvStatusInfo@494d84f)
2019-06-06 16:03:48.316 1930-1944/? I/GnssLOCATIOnProvider: WakeLock released by handlemessage(REPORT_SV_STATUS,com.android.server.LOCATIOn.GnssLOCATIOnProvider$SvStatusInfo@494d84f)

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

最佳答案
将此用于使用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();
}

大佬总结

以上是大佬教程为你收集整理的java-我可以在Android中使用POST方法从URL获取数据吗? 全部内容,希望文章能够帮你解决java-我可以在Android中使用POST方法从URL获取数据吗? 所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。