我想使用POST方法从URL提取数据.我已经使用GET方法获取了数据.现在,我想使用POST方法.当我单击按钮时,即使我提供了Internet许可,也没有任何响应.我认为还有其他问题.
我曾尝试搜索许多站点并观看教程,但是我所获得的只是如何使用POST方法将数据发送到服务器.
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://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>
我连续不断地在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();
}