php接收android数据,php – 使用6.0 API(Android)从服务器发送和接收数据

试试这个代码. 🙂

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

new Test().execute();

}

//AsyncTask

class Test extends AsyncTask < String, Void, String > {

@Override

protected String doInBackground(String...params) {

InputStream in = null;

String queryResult = "";

URL url = new URL("http://www.android.com/");

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

//add parameters

urlConnection.setReadTimeout(10000);

urlConnection.setConnectTimeout(15000);

urlConnection.setRequestMethod("POST");

urlConnection.setDoInput(true);

urlConnection.setDoOutput(true);

List params = new ArrayList();

params.add(new BasicNameValuePair("firstParam", paramValue1));

params.add(new BasicNameValuePair("secondParam", paramValue2));

params.add(new BasicNameValuePair("thirdParam", paramValue3));

try {

//write OutputStream

OutputStream os = urlConnection.getOutputStream();

BufferedWriter writer = new BufferedWriter(

new OutputStreamWriter(os, "UTF-8"));

writer.write(getQuery(params));

writer.flush();

writer.close();

os.close();

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

queryResult = readStream( in );

} finally {

urlConnection.disconnect();

}

return queryResult;

}

private String readStream(InputStream iStream) throws IOException {

//Buffered reader allows us to read line by line

try (BufferedReader bReader =

new BufferedReader(new InputStreamReader(iStream))) {

StringBuilder builder = new StringBuilder();

String line;

while ((line = bReader.readLine()) != null) { //Read till end

builder.append(line);

}

return builder.toString();

}

}

private String getQuery(List 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();

}

protected void onPostExecute(String data) {

// do further things

Toast toast = Toast.makeText(getApplicationContext(), data,

Toast.LENGTH_SHORT);

toast.show();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值