发送和接收使用6.0 API服务器的数据(Android版) [英] Send and receive data from server using 6.0 API (Android)
问题描述
我真的很困惑,我试图开发一个简单的函数,它让我从服务器发送和接收数据。
的操作如下:
在一个活动我执行一个HTTP POST到服务器上的PHP文件中,PHP文件得到我发送的数据(tipically字符串),并执行使用通过HTTP发送的参数的查询。
例如:
我的Android应用程序发送一个字符串,该值PIPPO,在PHP文件中有一个查询,例如:
$值= PIPPO / *从Android应用程序*接收到的数据/
选择字符*其中(characters.name =$价值。)
P.S。所有的数据使用JSON格式
的问题是:
我一直使用的功能(即正常工作),但现在所有的方法都是德precated,我无法找到的最新的API方法的选择。
这是我的code:
公共类ReadServer延伸活动{
字符串结果;
公共字符串readserver(字符串id_data,字符串数据){
尝试{
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httpPost =新HttpPost(myurl / queryMobile.php);
StringBuilder的建设者=新的StringBuilder();
JSON字符串=;
//构造的JSONObject
的JSONObject的JSONObject =新的JSONObject();
jsonObject.accumulate(id_data,数据);
//转换的JSONObject以JSON字符串来
JSON = jsonObject.toString(); //设置JSON来StringEntity
StringEntity SE =新StringEntity(JSON);
//设置httpPost实体
httpPost.setEntity(SE);
//设置一些头通知服务器有关内容的类型
httpPost.setHeader(接受,应用/ JSON);
httpPost.setHeader(内容类型,应用/ JSON); //执行POST请求到指定的URL
HTT presponse HTT presponse = httpclient.execute(httpPost);
//接收响应为InputStream的
状态行状态行= HTT presponse.getStatusLine();
INT状态code = statusLine.getStatus code();
//转换输入流串
AlertDialog.Builder alertDialog; 开关(状态code){
案例200:
HttpEntity实体= HTT presponse.getEntity();
InputStream的内容= entity.getContent();
读者的BufferedReader =新的BufferedReader(新的InputStreamReader(内容));
串线=;
尝试{
而((行= reader.readLine())!= NULL){
builder.append(线);
结果= builder.toString();
}
}赶上(例外五){
alertDialog =新AlertDialog.Builder(本);
alertDialog.setTitle(400错误的请求);
alertDialog.setMessage(非èstato不可能性soddisfare拉图阿richiesta,riprova彪tardi。);
alertDialog.show();
}
打破;
刚刚尝试这个code。 :)
公共类MainActivity扩展AppCompatActivity { @覆盖
保护无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
新的测试()执行();
}
// AsyncTask的
Test类扩展的AsyncTask<字符串,太虚,字符串> { @覆盖
保护字符串doInBackground(字符串... PARAMS){
在的InputStream = NULL;
串QueryResult中=;
网址URL =新的URL(http://www.android.com/);
HttpURLConnection类的URLConnection =(HttpURLConnection类)url.openConnection();
尝试{
在的InputStream =新的BufferedInputStream(urlConnection.getInputStream());
QueryResult中= readStream(上);
} {最后
urlConnection.disconnect();
}
返回QueryResult中; }
私人字符串readStream(InputStream中的IStream)抛出IOException //缓冲的读者可以让我们逐行读取
尝试(面包屑的BufferedReader =
新的BufferedReader(新的InputStreamReader(的IStream))){
StringBuilder的建设者=新的StringBuilder();
串线;
而((行= bReader.readLine())!= NULL){//读取直到结束
builder.append(线);
}
返回builder.toString();
}
}
保护无效onPostExecute(字符串数据){
//做进一步的事情
吐司面包= Toast.makeText(getApplicationContext(),数据,
Toast.LENGTH_SHORT);
toast.show(); } }}
I'm really confused, i'm trying to develop a simple function that allow me to send and receive data from a server.
The operation is as follows:
In an activity I execute an HTTP POST to a PHP file on a server, the "PHP file" gets the data that i send (tipically a string), and executes a query using the parameters sent over http.
Example:
My android app send a string with this value "PIPPO", in the PHP file there is a query, for example:
$value = PIPPO /* data received from android app*/ Select * from characters where(characters.name=".$value.")
p.s. all data use JSON format
The problem is: i always used a function (that works fine) but now all methods are deprecated, I can't find an alternative to the methods for the newest API.
This is my code:
public class ReadServer extends Activity {
String result;
public String readserver(String id_data, String data){
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl/queryMobile.php");
StringBuilder builder = new StringBuilder();
String json = "";
//Build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate(id_data, data);
//Convert JSONObject to JSON to String
json = jsonObject.toString();
//Set json to StringEntity
StringEntity se = new StringEntity(json);
//Set httpPost Entity
httpPost.setEntity(se);
//Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
//Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
//Receive response as inputStream
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
//Convert input stream to string
AlertDialog.Builder alertDialog;
switch(statusCode){
case 200:
HttpEntity entity = httpResponse.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line="";
try{
while ((line = reader.readLine()) != null) {
builder.append(line);
result = builder.toString();
}
}catch(Exception e){
alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("400 Bad Request");
alertDialog.setMessage("Non è stato possibile soddisfare la tua richiesta, riprova più tardi.");
alertDialog.show();
}
break;
Just try this code. :)
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();
try {
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();
}
}
protected void onPostExecute(String data) {
// do further things
Toast toast = Toast.makeText(getApplicationContext(), data,
Toast.LENGTH_SHORT);
toast.show();
}
}
}
这篇关于发送和接收使用6.0 API服务器的数据(Android版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!