Php 如何在android中使用HttpUrlconction发送请求以从服务器获取特定数据?
我是安卓的新手。有很多使用HttpClient、HttpPost从服务器获取数据的示例。但不幸的是,我找不到任何通过HttpUrlConnection从服务器获取特定数据的选项 我想知道, 如何从我的android应用程序将数据传递到服务器中的PHP文件 以及如何从PHP文件中读取该数据 我找到了一种方法,可以将查询到的数据从PHP文件重新发送到android应用程序,并使用json从android应用程序读取数据。获取请求:Php 如何在android中使用HttpUrlconction发送请求以从服务器获取特定数据?,php,android,Php,Android,我是安卓的新手。有很多使用HttpClient、HttpPost从服务器获取数据的示例。但不幸的是,我找不到任何通过HttpUrlConnection从服务器获取特定数据的选项 我想知道, 如何从我的android应用程序将数据传递到服务器中的PHP文件 以及如何从PHP文件中读取该数据 我找到了一种方法,可以将查询到的数据从PHP文件重新发送到android应用程序,并使用json从android应用程序读取数据。获取请求: InputStream is = null; URL url = n
InputStream is = null;
URL url = new URL( "http://my_url/index.php?par1=val1&par2=val2" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 20000 ); // if you want to set the Read timeout
conn.setConnectTimeout( 30000 ); // if you want to set the Connect timeout
conn.setRequestMethod( "GET" );
conn.setDoInput( true );
conn.connect();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK )
{
is = conn.getInputStream();
Reader reader = new InputStreamReader( is, "UTF-8" );
char[] buffer = new char[10240];
int len = reader.read( buffer );
// ...
}
if( is != null ) is.close();
URL url = new URL( address );
int len = params.getBytes().length;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches( false );
// conn.setDoInput( true ); // input channel needed?
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
conn.setRequestProperty( "charset", "utf-8" );
conn.setRequestProperty( "Content-Length", "" + Integer.toString( len ) );
conn.setFixedLengthStreamingMode( len );
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes( params );
dos.flush();
dos.close();
conn.disconnect();
后请求:
InputStream is = null;
URL url = new URL( "http://my_url/index.php?par1=val1&par2=val2" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 20000 ); // if you want to set the Read timeout
conn.setConnectTimeout( 30000 ); // if you want to set the Connect timeout
conn.setRequestMethod( "GET" );
conn.setDoInput( true );
conn.connect();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK )
{
is = conn.getInputStream();
Reader reader = new InputStreamReader( is, "UTF-8" );
char[] buffer = new char[10240];
int len = reader.read( buffer );
// ...
}
if( is != null ) is.close();
URL url = new URL( address );
int len = params.getBytes().length;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches( false );
// conn.setDoInput( true ); // input channel needed?
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
conn.setRequestProperty( "charset", "utf-8" );
conn.setRequestProperty( "Content-Length", "" + Integer.toString( len ) );
conn.setFixedLengthStreamingMode( len );
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes( params );
dos.flush();
dos.close();
conn.disconnect();
当然,尝试/捕获所需的异常
更新:示例Android POST参数“年龄”:
PHP行改为“年龄”:
获取请求:
InputStream is = null;
URL url = new URL( "http://my_url/index.php?par1=val1&par2=val2" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 20000 ); // if you want to set the Read timeout
conn.setConnectTimeout( 30000 ); // if you want to set the Connect timeout
conn.setRequestMethod( "GET" );
conn.setDoInput( true );
conn.connect();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK )
{
is = conn.getInputStream();
Reader reader = new InputStreamReader( is, "UTF-8" );
char[] buffer = new char[10240];
int len = reader.read( buffer );
// ...
}
if( is != null ) is.close();
URL url = new URL( address );
int len = params.getBytes().length;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches( false );
// conn.setDoInput( true ); // input channel needed?
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
conn.setRequestProperty( "charset", "utf-8" );
conn.setRequestProperty( "Content-Length", "" + Integer.toString( len ) );
conn.setFixedLengthStreamingMode( len );
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes( params );
dos.flush();
dos.close();
conn.disconnect();
后请求:
InputStream is = null;
URL url = new URL( "http://my_url/index.php?par1=val1&par2=val2" );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 20000 ); // if you want to set the Read timeout
conn.setConnectTimeout( 30000 ); // if you want to set the Connect timeout
conn.setRequestMethod( "GET" );
conn.setDoInput( true );
conn.connect();
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK )
{
is = conn.getInputStream();
Reader reader = new InputStreamReader( is, "UTF-8" );
char[] buffer = new char[10240];
int len = reader.read( buffer );
// ...
}
if( is != null ) is.close();
URL url = new URL( address );
int len = params.getBytes().length;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches( false );
// conn.setDoInput( true ); // input channel needed?
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded" );
conn.setRequestProperty( "charset", "utf-8" );
conn.setRequestProperty( "Content-Length", "" + Integer.toString( len ) );
conn.setFixedLengthStreamingMode( len );
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes( params );
dos.flush();
dos.close();
conn.disconnect();
当然,尝试/捕获所需的异常
更新:示例Android POST参数“年龄”:
PHP行改为“年龄”:
我找到了从服务器获取数据的方法 这是我的Android主要活动
package com.example.mfjaleel.myPackage;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
Button btn;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
tv = (TextView)findViewById(R.id.tv);
btn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
new JSONTask().execute("Ur link","parameters");
}
}
);
}
public class JSONTask extends AsyncTask<String,Void,String >{
ProgressDialog loading;
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
URL url ;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
//connection.connect();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
HashMap<String,String > data = new HashMap<String, String>();
data.put("id",params[1]);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(data));
writer.flush();
writer.close();
os.close();
int responseCode=connection.getResponseCode();
String response = "";
if (responseCode == HttpURLConnection.HTTP_OK) {
reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
response = reader.readLine();
}
else {
response="Error Registering";
}
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
return "MalformedURLException Exception";
} catch (IOException e) {
e.printStackTrace();
return "IO Exception";
}
//return "Error";
}
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait", null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
tv.setText(s);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
}
感谢您的帮助@mat和@greenapps我找到了从服务器获取数据的方法 这是我的Android主要活动
package com.example.mfjaleel.myPackage;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
Button btn;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button);
tv = (TextView)findViewById(R.id.tv);
btn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
new JSONTask().execute("Ur link","parameters");
}
}
);
}
public class JSONTask extends AsyncTask<String,Void,String >{
ProgressDialog loading;
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
URL url ;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
//connection.connect();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
HashMap<String,String > data = new HashMap<String, String>();
data.put("id",params[1]);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(data));
writer.flush();
writer.close();
os.close();
int responseCode=connection.getResponseCode();
String response = "";
if (responseCode == HttpURLConnection.HTTP_OK) {
reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
response = reader.readLine();
}
else {
response="Error Registering";
}
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
return "MalformedURLException Exception";
} catch (IOException e) {
e.printStackTrace();
return "IO Exception";
}
//return "Error";
}
@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait", null, true, true);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
tv.setText(s);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
}
感谢您的帮助@mat和@greenapps“我找到了一种方法,可以将查询到的数据从PHP文件重新发送到android应用程序,并使用json从android应用程序读取数据。”。那你就完了。您还需要什么?我想获取特定数据,例如,有一个名为“Person”的表,它具有“name”、“age”等属性,“城市”。然后我想找20岁以上的人。所以我想从我的Android应用程序发送20到php脚本来查询数据。我如何从android应用程序发送这20个数据,以及如何在服务器的PHP脚本中读取它。“我找到了一种方法,可以从PHP文件将查询到的数据重新发送到android应用程序,并使用json从android应用程序读取数据。”。那你就完了。您还需要什么?我想获取特定数据,例如,有一个名为“Person”的表,它具有“name”、“age”等属性,“城市”。然后我想找20岁以上的人。所以我想从我的Android应用程序发送20到php脚本来查询数据。我如何从android应用程序发送20个,以及如何在服务器中的PHP脚本中读取它。感谢您的回复。那么如何从服务器中的PHP脚本读取这些数据?@MFaizan:尝试从
var\u dump($\u请求)开始代码>-然后深入查看PHP或搜索其他问题,有很多类似的请求。什么是参数?没有人能看到您正在发送的数据。例如,没有20。Params是带有参数的字符串,例如:stringparams=“par1=val1&par2=val2”代码>-什么是20?谢谢你的回复。那么如何从服务器中的PHP脚本读取这些数据?@MFaizan:尝试从var\u dump($\u请求)开始代码>-然后深入查看PHP或搜索其他问题,有很多类似的请求。什么是参数?没有人能看到您正在发送的数据。例如,没有20。Params是带有参数的字符串,例如:stringparams=“par1=val1&par2=val2”代码>-什么是20?