[英]Can I fetch data from URL using POST method in Android?
I want to fetch data from a URL using the POST method. 我想使用POST方法从URL获取数据。 I already fetched data using the GET method. 我已经使用GET方法获取数据。 Now I want to do it with the POST method. 现在我想用POST方法做到这一点。 When I click on the button I don't get any response even though I have provided internet permission. 当我点击按钮时,即使我提供了互联网许可,我也没有得到任何回复。 I think there's some other problem. 我认为还有其他一些问题。
I have tried searching many sites and watching tutorials, but all I get is how to send data to the server using the POST method. 我尝试过搜索许多网站并观看教程,但我得到的是如何使用POST方法将数据发送到服务器。
MainActivity.java 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);
}
}
Async.java Async.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 activity_main.xml中
<?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>
I am getting this error continuously in logcat for like unlimited times. 我在logcat中连续无限次地收到此错误。
2019-06-06 16:03:48.315 1930-2875/? I/GnssLocationProvider: WakeLock acquired by sendMessage(REPORT_SV_STATUS, 0, 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, 0, com.android.server.location.GnssLocationProvider$SvStatusInfo@494d84f)
I want the fetched data in the textview but I am not able to see even the text written in textview. 我想在textview中获取所获取的数据,但我甚至无法看到textview中写的文本。
Use this for POST request using HttpURLConnection, you can add or remove properties based on your requirement: 使用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();
Here is getQuery() method : 这是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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.