Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/206.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
使用JSON从Android应用程序向服务器发送数据_Android_Json_Http Post - Fatal编程技术网

使用JSON从Android应用程序向服务器发送数据

使用JSON从Android应用程序向服务器发送数据,android,json,http-post,Android,Json,Http Post,我正在尝试从android应用程序在本地服务器中插入数据。我正在测试我的应用程序的post方法。当我发送数据时会显示这些数据,但当我在本地服务器上测试我的应用程序时,它不会显示数据。可能我的应用程序没有以JSON数组格式发送数据。我正在遵循来自的相同代码。下面列出了我为访问本地服务器而编辑的代码 @Override public void onClick(View view) { switch(view.getId()){ case R.id.btnPost:

我正在尝试从android应用程序在本地服务器中插入数据。我正在测试我的应用程序的post方法。当我发送数据时会显示这些数据,但当我在本地服务器上测试我的应用程序时,它不会显示数据。可能我的应用程序没有以JSON数组格式发送数据。我正在遵循来自的相同代码。下面列出了我为访问本地服务器而编辑的代码

@Override
public void onClick(View view) {

    switch(view.getId()){
        case R.id.btnPost:
            if(!validate())
                Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
            // call AsynTask to perform network operation on separate thread
            new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
            break;
    }

}

在这里,此代码不会生成任何错误消息,它显示的是发送的Toast消息数据。 谁能告诉我解决办法吗?非常感谢您的及时回复。

请尝试此功能

 public String request(String url, List<NameValuePair> nameValuePairs) {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        // httpPost.setHeader("encytype", "multipart/form-data");

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
        httpPost.setEntity(entity);

        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        reader.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Buffer Error" + "Error converting result " + e.toString());
    }

    return json;
}
公共字符串请求(字符串url,列表nameValuePairs){
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
//setHeader(“百科类型”、“多部分/表单数据”);
HttpParams httpParameters=新的BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);
UrlEncodedFormEntity实体=新的UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
httpPost.setEntity(实体);
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8;
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
reader.close();
json=sb.toString();
}捕获(例外e){
Log.e(“Log_标记”,“缓冲区错误”+“错误转换结果”+e.toString());
}
返回json;
}

虽然这不是一个正确的答案,但您可以尝试一下,这是一个有效的代码,它使用了建议的HttpUrlConnection:

public static String postJSON(String myurl, JSONArray jarr) throws IOException {
        StringBuffer response = null;
        try {
            JSONObject parameters = new JSONObject();
            parameters.put("phoneType", "Android");
            parameters.put("jsonArray", jarr);
            parameters.put("key", "testkey");
            parameters.put("mail", "xyz@gmail.com");

            URL url = new URL(myurl);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            OutputStream out = new BufferedOutputStream(conn.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(parameters.toString());
            System.out.println("params.tostring" + parameters.toString());

            writer.close();
            out.close();

            int responseCode = conn.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            System.out.println("Response in universal: " + response.toString());
        } catch (Exception exception) {
            System.out.println("Exception: " + exception);
        }

        return response.toString();
    }
在php方面:

<?php



    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    print_r($obj);
    print_r("this is a test");
?>

我建议您将此项目用作库:

它非常简单,我所有的项目都使用它!它正在不断改进

尽快(也许这周)我会做一个更新,以适应Android Studio


我希望有帮助

这是不推荐的,您必须使用HttpUrlConnection();HttpClient已弃用,您必须使用HttpUrlConnection()使用Volley以获得快速高效的结果,请参阅此链接
<?php



    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    print_r($obj);
    print_r("this is a test");
?>