问题描述
使用此处定义的Volley 。这要容易得多。
解决方法
我几天前才刚开始学习android,但是我将JSON数据上传到服务器时遇到了问题。我设法通过以下代码检索它:
编辑:我确实设法使用外部OKHTTP库检索文件,但是我想这样做而不使用外部库。
package cc.demorest;
import android.os.AsyncTask;
import android.renderscript.ScriptGroup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
task.execute("myserver.com");
}
//Downloadtask
public class DownloadTask extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection=null;
try {
url = new URL(urls[0]);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data=reader.read();
while (data !=-1){
char current=(char) data;
result += current;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//After download task
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONArray jArray=new JSONArray(result);
JSONObject json_data = jArray.getJSONObject(1);
//Logging data
Log.i("Podatci: ","Id: " + json_data.getInt("Id") +
",Name: " + json_data.getString("Name") +
",Years: " + json_data.getString("Age") +
",Email address: " + json_data.getString("Email")
);
TextView textView = (TextView) findViewById(R.id.textViewName);
textView.setText("ID: "+",Name: "+ json_data.getInt("Id")+json_data.getString("Name")+json_data.getString("Age")+json_data.getString("Email"));
/*
String data = jsonObject.getString("Name");
Log.i("Website content",data);
*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
我现在正尝试将数据发送到具有相同字段的相同服务器。我搜索了互联网,但是发现的大多数东西都已经过时了。我真的很想提供一些帮助或示例。最好的祝福