Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/211.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Android通过请求发送JSON对象?_Android_Json_Post_Httprequest - Fatal编程技术网

如何使用Android通过请求发送JSON对象?

如何使用Android通过请求发送JSON对象?,android,json,post,httprequest,Android,Json,Post,Httprequest,我想发送以下JSON文本 {"Email":"aaa@tbbb.com","Password":"123456"} 访问web服务并读取响应。我知道如何阅读JSON。问题是上述JSON对象必须以变量名jason发送 我如何在安卓上做到这一点?创建请求对象、设置内容头等步骤是什么。Android没有发送和接收HTTP的特殊代码,您可以使用标准Java代码。我建议使用Android附带的Apache HTTP客户端。下面是我用来发送HTTP POST的代码片段 我不明白在名为“jason”的变量中

我想发送以下JSON文本

{"Email":"aaa@tbbb.com","Password":"123456"}
访问web服务并读取响应。我知道如何阅读JSON。问题是上述JSON对象必须以变量名
jason
发送


我如何在安卓上做到这一点?创建请求对象、设置内容头等步骤是什么。

Android没有发送和接收HTTP的特殊代码,您可以使用标准Java代码。我建议使用Android附带的Apache HTTP客户端。下面是我用来发送HTTP POST的代码片段

我不明白在名为“jason”的变量中发送对象与任何事情有什么关系。如果您不确定服务器需要什么,请考虑编写一个测试程序来发送各种字符串到服务器,直到您知道它需要什么格式。

int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
String postMessage="{}"; //HERE_YOUR_POST_STRING.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
    postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);

如果使用ApacheHTTP客户端,从Android发送json对象很容易。这里有一个关于如何做的代码示例。您应该为网络活动创建一个新线程,以免锁定UI线程

    protected void sendJson(final String email, final String pwd) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                JSONObject json = new JSONObject();

                try {
                    HttpPost post = new HttpPost(URL);
                    json.put("email", email);
                    json.put("password", pwd);
                    StringEntity se = new StringEntity( json.toString());  
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /*Checking response */
                    if(response!=null){
                        InputStream in = response.getEntity().getContent(); //Get the data in the entity
                    }

                } catch(Exception e) {
                    e.printStackTrace();
                    createDialog("Error", "Cannot Estabilish Connection");
                }

                Looper.loop(); //Loop in the message queue
            }
        };

        t.start();      
    }

您还可以使用发送和检索JSON

下面的链接提供了一个非常好的Android HTTP库:

public void postData(String url,JSONObject obj) {
    // Create a new HttpClient and Post Header

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClient httpclient = new DefaultHttpClient(myParams );
    String json=obj.toString();

    try {

        HttpPost httppost = new HttpPost(url.toString());
        httppost.setHeader("Content-type", "application/json");

        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se); 

        HttpResponse response = httpclient.execute(httppost);
        String temp = EntityUtils.toString(response.getEntity());
        Log.i("tag", temp);


    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }
}

简单的请求非常容易:

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        System.out.println(response);
    }
});
要发送JSON(请登录“voidberg”,网址为):


它完全是异步的,与Android配合良好,可以从UI线程安全地调用。responseHandler将在创建它的同一线程(通常是UI线程)上运行。它甚至有一个内置的JSON resonseHandler,但我更喜欢使用google gson。

HttpPost
被Android Api Level 22弃用。因此,使用
HttpUrlConnection
了解更多信息

public static String makeRequest(String uri, String json) {
    HttpURLConnection urlConnection;
    String url;
    String data = json;
    String result = null;
    try {
        //Connect 
        urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();

        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

现在,由于不推荐使用
HttpClient
,当前的工作代码是使用
HttpUrlConnection
创建连接,并写入和读取连接。但我更喜欢用这个。此库来自android AOSP。我发现制作
JsonObjectRequest
JsonArrayRequest

非常简单。使用OkHttpLibrary

创建json

JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);
像这样发送

OkHttpClient client = new OkHttpClient();

RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
            .addHeader("Content-Type","application/json")
            .url(url)
            .post(requestObject.toString())
            .build();

okhttp3.Response response = client.newCall(request).execute();
公共类getUserProfile扩展了异步任务{
JSONArray阵列;
@凌驾
受保护的JSONArray doInBackground(无效…参数){
试一试{
commonurl cu=新的commonurl();
字符串u=cu.geturl(“tempshowusermain.php”);
URL=新URL(u);
//URL=新URL(“http://192.168.225.35/jabber/tempshowusermain.php");
HttpURLConnection HttpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod(“POST”);
setRequestProperty(“内容类型”、“应用程序/json”);
setRequestProperty(“接受”、“应用程序/json”);
httpURLConnection.setDoOutput(true);
setRequestProperty(“连接”,“保持活动”);
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
JSONObject JSONObject=新的JSONObject();
jsonObject.put(“lid”,lid);
DataOutputStream outputStream=新的DataOutputStream(httpURLConnection.getOutputStream());
write(jsonObject.toString().getBytes(“UTF-8”);
int code=httpURLConnection.getResponseCode();
如果(代码==200){
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(httpURLConnection.getInputStream());
StringBuffer StringBuffer=新的StringBuffer();
弦线;
而((line=bufferedReader.readLine())!=null){
stringBuffer.append(行);
}
object=newJSONObject(stringBuffer.toString());
//数组=新的JSONArray(stringBuffer.toString());
array=object.getJSONArray(“响应”);
}
}捕获(例外e){
e、 printStackTrace();
}
返回数组;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的void onPostExecute(JSONArray数组){
onPostExecute(数组);
试一试{
对于(int x=0;x
Hi服务器可能会要求我设置一个头标JSON并将JSON放在
OkHttpClient client = new OkHttpClient();

RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
            .addHeader("Content-Type","application/json")
            .url(url)
            .post(requestObject.toString())
            .build();

okhttp3.Response response = client.newCall(request).execute();
public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
    JSONArray array;
    @Override
    protected JSONArray doInBackground(Void... params) {

        try {
            commonurl cu = new commonurl();
            String u = cu.geturl("tempshowusermain.php");
            URL url =new URL(u);
          //  URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("lid",lid);


            DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            outputStream.write(jsonObject.toString().getBytes("UTF-8"));

            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                StringBuffer stringBuffer = new StringBuffer();
                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                object =  new JSONObject(stringBuffer.toString());
             //   array = new JSONArray(stringBuffer.toString());
                array = object.getJSONArray("response");

            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return array;


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();



    }

    @Override
    protected void onPostExecute(JSONArray array) {
        super.onPostExecute(array);
        try {
            for (int x = 0; x < array.length(); x++) {

                object = array.getJSONObject(x);
                ComonUserView commUserView=new ComonUserView();//  commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
                //pidArray.add(jsonObject2.getString("pid").toString());

                commUserView.setLid(object.get("lid").toString());
                commUserView.setUname(object.get("uname").toString());
                commUserView.setAboutme(object.get("aboutme").toString());
                commUserView.setHeight(object.get("height").toString());
                commUserView.setAge(object.get("age").toString());
                commUserView.setWeight(object.get("weight").toString());
                commUserView.setBodytype(object.get("bodytype").toString());
                commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
                commUserView.setImagepath(object.get("imagepath").toString());
                commUserView.setDistance(object.get("distance").toString());
                commUserView.setLookingfor(object.get("lookingfor").toString());
                commUserView.setStatus(object.get("status").toString());

                cm.add(commUserView);
            }
            custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
          gridusername.setAdapter(custuserprof);
            //  listusername.setAdapter(custuserprof);
            } catch (Exception e) {

                e.printStackTrace();
        }
    }