更新时间:2022-11-28 12:34:18
刚刚尝试这个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();
}
}
}