繁体   English   中英

Android Studio中的POST请求示例

[英]Example of POST request in Android studio

我几天前才刚刚开始学习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();
        }

        }
    }



}

我现在正尝试将数据发送到具有相同字段的相同服务器。 我搜索了Internet,但是发现的大多数东西都已经过时了。.我真的很希望能提供一些帮助或示例。 最好的祝福

使用HttpURLConnection ,它不使用外部库。 如果要使用HttpURLConnection,则它必须是AsyncTask

这是我完成的项目中的代码。 希望能帮助到你。

首先,将其放在您的manifest.xml文件中:

<uses-permission android:name="android.permission.INTERNET" />

调用AsyncTask:

(忽略this,SinceTime和GoesAddress。它们只是我传入的变量)

    URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
    new ReceiveData(this, SinceTime, GoesAddress).execute(url);

班级:

package com.ryan.scrapermain;

import android.content.Context;
import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;


public class ReceiveData extends AsyncTask<URL, Integer, Long> {

    String response = "";
    String SinceTime;
    String GoesAddress;
    Context myContext;

    ReceiveData(Context context, String since, String goes) {
        this.myContext = context;
        SinceTime = since;
        GoesAddress = goes;
        }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder feedback = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                feedback.append("&");

            feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            feedback.append("=");
            feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return feedback.toString();
    }

    public void getData() throws IOException {

        HashMap<String, String> params = new HashMap<>();
        params.put("DCPID", GoesAddress);
        params.put("SINCE", SinceTime);

        URL url = new URL("https://eddn.usgs.gov/cgi-bin/fieldtest.pl");
        HttpURLConnection client = null;
        try {
            client = (HttpURLConnection) url.openConnection();
            client.setRequestMethod("POST");
            // You need to specify the context-type.  In this case it is a
            // form submission, so use "multipart/form-data"
            client.setRequestProperty("multipart/form-data", "https://eddn.usgs.gov/fieldtest.html;charset=UTF-8");
            client.setDoInput(true);
            client.setDoOutput(true);

            OutputStream os = client.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(params));

            writer.flush();
            writer.close();
            os.close();
            int responseCode = client.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            }
            else {
                response = "";
            }
        }
        catch (MalformedURLException e){
            e.printStackTrace();
        }
        finally {
            if(client != null) // Make sure the connection is not null.
                client.disconnect();
        }
    }

    @Override
    protected Long doInBackground(URL... params) {
        try {
            getData();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // This counts how many bytes were downloaded
        final byte[] result = response.getBytes();
        Long numOfBytes = Long.valueOf(result.length);
        return numOfBytes;
    }

    protected void onPostExecute(Long result) {
        System.out.println("Downloaded " + result + " bytes");
        // This is just printing it to the console for now.
        System.out.println(response);
        // In the following two line I pass the string elsewhere and decode it.
        InputCode input = new InputCode();
        input.passToDisplay(myContext, response);
    }
}

使用此处定义的Volley。 这要容易得多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM