我是JSON Web服务的新手。我正在传递参数并从服务器获取数据。 找到下面的代码。
在清单中添加了互联网权限。
可以帮助我使用带参数的post方法从服务器获取数据的示例代码。
出于安全原因,我在下面更改了网址详情。
请在这里帮助我。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
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) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
TextView textview=(TextView)findViewById(R.id.textview);
URL url=new URL("https://XXXX.net/XXX");
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
String urlparameters="version=1.0&apikey=isjd&src=test.shoppinglist&apiname=nen&category=all";
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT","Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE","en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dstream=new DataOutputStream(connection.getOutputStream());
dstream.writeBytes(urlparameters);
dstream.flush();
dstream.close();
int request_code=connection.getResponseCode();
String output="Request URL:"+url;
output+=System.getProperty("line.separator")+" Request Parameters:"+urlparameters;
output+=System.getProperty("line.separator")+" RequestCOde:"+request_code;
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line="";
StringBuilder ResponseOutput=new StringBuilder();
while((line=br.readLine())!=null){
ResponseOutput.append(line);
}
br.close();
output +=System.getProperty("line.separator")+ ResponseOutput.toString();
textview.setText(output);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}